在 ArrayList 中创建 ArrayList

发布于 2024-11-25 01:37:40 字数 1702 浏览 1 评论 0原文

因此,对于我正在开发的程序,我试图创建一个可以解析文本文件的方法。使用文本文件中的值,在 ArrayList 内创建一个 ArrayList。这是到目前为止我的代码:

public ArrayList<ArrayList<String>> getRels(String relsFile)
{
   String[] currentId;
   int i = -1;

   ArrayList<ArrayList<String>> relsList = new ArrayList<ArrayList<String>>();
   relsList.add(new ArrayList<String>());

   try
   {
      // Open the file that is the first 
      // command line parameter
      FileInputStream fstream = new FileInputStream(relsFile);
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
      String strLine;

      while ((strLine = br.readLine()) != null)
      {
         // Add values to array list
         currentId = strLine.split(",");
         relsList.get(++i).add(currentId[0]);
         //???????????          
      }   
      //Close the input stream
      in.close();
   }        
   catch (Exception e)
   {
      System.err.println("Error: " + e.getMessage());
   }
   return relsList; 
}

这是我正在查看的文本文件的示例。

rId13,image3
rId18,image8
rId26,image16
rId39,image29
rId21,image11
rId34,image24
rId7,image1
rId12,image2
rId17,image7
rId25,image15
rId33,image23
rId38,image28
rId16,image6
rId20,image10
rId29,image19
rId24,image14
rId32,image22
rId37,image27
rId15,image5
rId23,image13
rId28,image18
rId36,image26
rId19,image9
rId31,image21
rId14,image4
rId22,image12
rId27,image17
rId30,image20
rId35,image25

本质上,我希望能够拆分这些值,将所有 rId 值存储在第一个 ArrayList 中,然后列出它们相应的 image 值嵌套的ArrayList。然而,我有点陷入困境,不知道此时该怎么办。有人可以帮我吗?我感谢您提供的任何帮助。

So for a program I am working on, I am trying to create a method which will parse through a text file. Using the values within the text file, create an ArrayList within an ArrayList. Here is my code so far:

public ArrayList<ArrayList<String>> getRels(String relsFile)
{
   String[] currentId;
   int i = -1;

   ArrayList<ArrayList<String>> relsList = new ArrayList<ArrayList<String>>();
   relsList.add(new ArrayList<String>());

   try
   {
      // Open the file that is the first 
      // command line parameter
      FileInputStream fstream = new FileInputStream(relsFile);
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
      String strLine;

      while ((strLine = br.readLine()) != null)
      {
         // Add values to array list
         currentId = strLine.split(",");
         relsList.get(++i).add(currentId[0]);
         //???????????          
      }   
      //Close the input stream
      in.close();
   }        
   catch (Exception e)
   {
      System.err.println("Error: " + e.getMessage());
   }
   return relsList; 
}

And here is an example of the text file I am looking at.

rId13,image3
rId18,image8
rId26,image16
rId39,image29
rId21,image11
rId34,image24
rId7,image1
rId12,image2
rId17,image7
rId25,image15
rId33,image23
rId38,image28
rId16,image6
rId20,image10
rId29,image19
rId24,image14
rId32,image22
rId37,image27
rId15,image5
rId23,image13
rId28,image18
rId36,image26
rId19,image9
rId31,image21
rId14,image4
rId22,image12
rId27,image17
rId30,image20
rId35,image25

Essentially, I want to be able to split up the values, store all rId values in the first ArrayList, then list their corresponding image values in the nested ArrayList. However, I am kind of stuck and not sure what to do at this point. Could someone help me out? I appreciate any help that is offered.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

氛圍 2024-12-02 01:37:40

我建议您使用调试器来准确查看发生了什么。

通过阅读代码,我猜测它可以正常读取第一行,但在那之后会失败,因为您只添加一个嵌套的 ArrayList 但尝试使用其中的许多。

最简单的做法是返回 Map;因为我假设第一列是唯一的。

public static Map<String, String> getRels(String relsFile) {
    Map<String, String> map = new LinkedHashMap<String, String>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(relsFile));
        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(",", 2);
            if (parts.length > 1)
                map.put(parts[0], parts[1]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) br.close();
        } catch (IOException ignored) {
        }
    }
    return map;
}

I suggest you use a debugger to see exactly what is happening.

From reading the code I would guess it reads the first line okay but fails after that point because you only add one nested ArrayList but try to use many of them.

The simplest thing to do is to return Map<String, String> as I assume the first column is unique.

public static Map<String, String> getRels(String relsFile) {
    Map<String, String> map = new LinkedHashMap<String, String>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(relsFile));
        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(",", 2);
            if (parts.length > 1)
                map.put(parts[0], parts[1]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) br.close();
        } catch (IOException ignored) {
        }
    }
    return map;
}
糖果控 2024-12-02 01:37:40

创建两个数组列表。填充它们..然后将它们添加到您的其他数组列表中。

话虽这么说,那必须是一个数组列表吗?你不能只拥有一个包含两个不同数组列表的常规对象吗?更好的是,也许您想考虑不同的数据结构本身,例如 Map ?

    try
    {
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream(relsFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;

        ArrayList<String> list1 = new ArrayList<String>();
        ArrayList<String> list2 = new ArrayList<String>();

        while ((strLine = br.readLine()) != null)
        {
            // Add values to array list
            currentId = strLine.split(",");
            list1.add(currentId[0]);
            list2.add(currentId[1]);

        }     
        //Close the input stream
        in.close();

       relsList.add(list1);
       relsList.add(list2);
    }       

Create the two arraylists. Populate them .. then add them into your other arraylist.

That being said, does that have to be an arraylist? Can't you just have a regular object that contains two different arraylists ? Even better, maybe you want to consider a different data structure itself like a Map ?

    try
    {
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream(relsFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;

        ArrayList<String> list1 = new ArrayList<String>();
        ArrayList<String> list2 = new ArrayList<String>();

        while ((strLine = br.readLine()) != null)
        {
            // Add values to array list
            currentId = strLine.split(",");
            list1.add(currentId[0]);
            list2.add(currentId[1]);

        }     
        //Close the input stream
        in.close();

       relsList.add(list1);
       relsList.add(list2);
    }       
趴在窗边数星星i 2024-12-02 01:37:40

我认为完成此任务的更好方法是使用任何现有的库来读取 CSV 文件。这将使您的代码更加简单。

I think a better way of doing this task is to use any of the already existing libraries for reading from CSV files. This will make your code much simpler.

活泼老夫 2024-12-02 01:37:40

我同意 Peter L 的观点 - 绝对使用 Map 实现。我使用 TreeMap 进行测试,因为它是排序的 Map,但您可以使用任何您想要的 Map。我还对此进行了测试以确保它有效。

根据您的描述,我相信这就是您想要的:

public TreeMap<String, ArrayList<String>> getRels(String relsFile)
{
    String[] currentId;
    int i = -1;

    TreeMap<String, ArrayList<String>> relsList = new TreeMap<String, ArrayList<String>>();

    try
    {
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream(relsFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;

        while ((strLine = br.readLine()) != null)
        {
            // Add values to array list
            currentId = strLine.split(",");
            if(relsList.containsKey(currentId[0])) {
                relsList.get(currentId[0]).add(currentId[1]);
            } else {
                relsList.put(currentId[0], new ArrayList<String>());
                relsList.get(currentId[0]).add(currentId[1]);
            }

        }     
        //Close the input stream
        in.close();
    }       
    catch (Exception e)
    {
        System.err.println("Error: " + e.getMessage());
    }
    return relsList;    
}

public static void main(String[] args) {
    ListReader lr = new ListReader();
    TreeMap<String, ArrayList<String>> l = lr.getRels("test.txt");
    for(String s : l.keySet()) {
        for(String k : l.get(s)) {
            System.out.println("Key: " + s + " Value: " + k);
        }
    }
}

我在解析部分所做的是使用简单的 IF...ELSE 语句解析文件。它检查键是否已经存在(rId 部分),如果存在,它只是将右侧的值添加到现有的 ArrayList 中。如果没有,它会添加一个新键,然后创建一个 ArrayList,然后将值添加到其中。

希望这就是您想要的!

I agree with Peter L - definitely use a Map implementation. I used a TreeMap for testing purposes since it's a sorted Map, but you can use whichever Map you want. I also tested this to make sure it worked.

From your description, I believe this is what you want:

public TreeMap<String, ArrayList<String>> getRels(String relsFile)
{
    String[] currentId;
    int i = -1;

    TreeMap<String, ArrayList<String>> relsList = new TreeMap<String, ArrayList<String>>();

    try
    {
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream(relsFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;

        while ((strLine = br.readLine()) != null)
        {
            // Add values to array list
            currentId = strLine.split(",");
            if(relsList.containsKey(currentId[0])) {
                relsList.get(currentId[0]).add(currentId[1]);
            } else {
                relsList.put(currentId[0], new ArrayList<String>());
                relsList.get(currentId[0]).add(currentId[1]);
            }

        }     
        //Close the input stream
        in.close();
    }       
    catch (Exception e)
    {
        System.err.println("Error: " + e.getMessage());
    }
    return relsList;    
}

public static void main(String[] args) {
    ListReader lr = new ListReader();
    TreeMap<String, ArrayList<String>> l = lr.getRels("test.txt");
    for(String s : l.keySet()) {
        for(String k : l.get(s)) {
            System.out.println("Key: " + s + " Value: " + k);
        }
    }
}

What I've done in the parsing part is parse the file with a simple IF...ELSE statement. It checks to see if the key already exists (the rId part) and if it does, it simply adds the value on the right to the existing ArrayList. If not, it adds a new key and then creates an ArrayList, which it then adds the value to.

Hopefully this is what you want!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文