how to work with Multidimensional arraylist?

陌路散爱 提交于 2020-01-15 22:50:38

问题


Hey guys sorry i'm a noob at java but im trying to make something and i need a multidimensional array list. It must be implemented into the following code:

public static void OpenFile() {
 ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
    int retrival = chooser.showOpenDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try (BufferedReader br = new BufferedReader(new FileReader(
                chooser.getSelectedFile()))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                if (sCurrentLine.equals("")) {
                    continue;
                } else if (sCurrentLine.startsWith("Question")) {
                    System.out.println(sCurrentLine.split(":")[1]);
                    //add to [0] in array ArrayList
                } else if (sCurrentLine.startsWith("Answer")) {
                    System.out.println(sCurrentLine.split(":")[1]);
                    //add to [1] in array ArrayList
                } else if (sCurrentLine.startsWith("Category")) {
                    System.out.println(sCurrentLine.split(":")[1]);
                    //add to [2] in array ArrayList
                } else if (sCurrentLine.startsWith("Essay")) {
                    System.out.println(sCurrentLine.split(":")[1]);
                    //add to [3] in array ArrayList
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

All the [1] index's of the strings i split need to go into a multidimesional array in this order: question, answer, category, essay.
So i am currently using a normal multidimensional array but you cant change the values of it easily. What i want my multidimensional arraylist to look like is this:

MultiDimensional ArrayList

  • [0]: questions(it may be over 100 of them.)
  • [1] answers(it may be over 100 of them.)
  • [2] category(it may be over 100 of them.)
  • [3] essay(it may be over 100 of them.)

回答1:


Seems like an assignment with List of List.

Here is the psuedo code. Try to implement rest.

 ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();

First thing you have to do is take 4 fresh ArrayLists

 ArrayList<String> qtns= new ArrayList<String>>();
 ArrayList<String> answrs= new ArrayList<String>>();
--
--

Add all of them to main list

array.add(qtns);
--
--

Then now filling them like

     else if (sCurrentLine.startsWith("Question")) {
                        System.out.println(sCurrentLine.split(":")[1]);
                        //add to [0] in array ArrayList
                        array.get(0).add(sCurrentLine.split(":")[1]);//get first list(which is qtns list) and add to it.
     } else if (sCurrentLine.startsWith("Answer")) {
                    System.out.println(sCurrentLine.split(":")[1]);
                    //add to [1] in array ArrayList
 array.get(1).add(sCurrentLine.split(":")[1]);//get second list(which is answers list) and add to it.
                }
    -- -
    ---

So that in the end you'll have a list of list which contains the data.




回答2:


array is an array of four elements (or will be, after you set it up--see below). Each of the elements is a reference to another ArrayList, i.e. an ArrayList<String>. To modify the inner ArrayList, first you need to get the reference to it, which you do with the get method:

array.get(0)

for the [0] list, or array.get(1) for the [1] list, and so on. The result will be an ArrayList<String>. Now you can perform methods on that; to add a String to the end of the ArrayList<String>:

array.get(0).add("String to add");

etc.

Actually, now that I look at it, you'll need to set up the four elements of array first. Each element will be set to a new ArrayList<String>:

for (int i = 0; i < 4; i++)
    array.add(new ArrayList<String>());

Do this at the top of the method.




回答3:


This is a really bad design. You should create a custom class, with the separate types of rows as fields (maybe call it Question), and then use a List<Question> to store the individual question objects. This will make it clearer, and safer, to work with in the future.




回答4:


You can have a HashMap with key as (Questions,Answers..) and ArrayList as value

HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();


 if(array.containsKey("Question")){
         array.get("Question").add(sCurrentLine.split(":")[1]);
  }else{
          ArrayList<String> questions = new ArrayList<String>();
          questions.add(sCurrentLine.split(":")[1]);
          array.put("Question",questions );
 }

Modification In your Code

public static void OpenFile() {
        HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();
        int retrival = chooser.showOpenDialog(null);
        if (retrival == JFileChooser.APPROVE_OPTION) {
            try (BufferedReader br = new BufferedReader(new FileReader(
                    chooser.getSelectedFile()))) {
                String sCurrentLine;
                while ((sCurrentLine = br.readLine()) != null) {
                    if (sCurrentLine.equals("")) {
                        continue;
                    } else if (sCurrentLine.startsWith("Question")) {
                        System.out.println(sCurrentLine.split(":")[1]);
                        if(array.containsKey("Question")){
                            array.get("Question").add(sCurrentLine.split(":")[1]);
                        }else{
                            ArrayList<String> questions = new ArrayList<String>();
                            questions.add(sCurrentLine.split(":")[1]);
                            array.put("Question",questions );
                        }
                        //add to [0] in array ArrayList
                    } else if (sCurrentLine.startsWith("Answer")) {
                        System.out.println(sCurrentLine.split(":")[1]);
                        //add to [1] in array ArrayList
                        //Do the same as above if condition with Answer as Key
                    } else if (sCurrentLine.startsWith("Category")) {
                        System.out.println(sCurrentLine.split(":")[1]);
                        //add to [2] in array ArrayList
                    } else if (sCurrentLine.startsWith("Essay")) {
                        System.out.println(sCurrentLine.split(":")[1]);
                        //add to [3] in array ArrayList
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }



回答5:


Once you created a 2D array, you also need to create 4 1D arrays.

ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// 1D array for "Question"
array.add(new ArrayList<String>());
// 1D array for "Answer"
array.add(new ArrayList<String>());
// 1D array for "Category"
array.add(new ArrayList<String>());
// 1D array for "Essay"
array.add(new ArrayList<String>());

Let's say if you need to add one item to the question array, then you should do:

array.get(i).add(...);

where i = 0. The range of i is from 0 to 3, which corresponds to the 4 enumerations.




回答6:


You should use another data structure to achieve that, Use a Map<String,List<String>> where the possible keys are Question,Answers,Category,Essay

Then in your code you can remove all unnecessary if-else

Example with your code:

public static void openFile() {
    Map<String,List<String>> map = new HashMap<>();
    // here you put the keys, you can do it when you read the file based in your input too dynamically
    map.put("Question",new ArrayList<>());
    map.put("Answers",new ArrayList<>());
    map.put("Category",new ArrayList<>());
    map.put("Essay",new ArrayList<>());
    int retrival = chooser.showOpenDialog(null);
    String[]array = null;
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try (BufferedReader br = new BufferedReader(new FileReader(
                chooser.getSelectedFile()))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                if (sCurrentLine.equals("")) {
                    continue;
                }

               array = sCurrentLine.split(":");
               if(map.containsKey(array[0])){
                  map.get(array[0]).add(array[1]);
               }   
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

You can see this way is much more cleaner and readable.



来源:https://stackoverflow.com/questions/20862515/how-to-work-with-multidimensional-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!