Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java array of arraylists

I have four columns of buttons in my program. Buttons move between columns when assigned new ones. Instead of declaring 4 separate arraylists to store the buttons, is there a way to create 1 array of arraylists so I can simply itterate through the array?

I've tried List<JButton>[] lists = new ArrayList<JButton>[5];

But that won't work. What am I missing?

EDIT:

for(int i = 0; i < 5; i++){
            if(choiceList.getSelectedIndex() == i){
                if(btnPersons[nameList.getSelectedIndex()].getX() == column[i]){
                    JOptionPane.showMessageDialog(null, "Error - Name already present in the column.","", 1);
                }else{
                    for(int j = 0; j < 5; j++){
                        if(lists[j].get(i) != null){
                            lists[j].remove(btnPersons[nameList.getSelectedIndex()]);
                        }
                    }
                    lists[i].add(btnPersons[nameList.getSelectedIndex()]);
                    lists[i].get(i).setBounds(column[i], ROWS[i], 125, 20);
                    //reloadLocations();
                }
            }
        }

This is my code currently.Once a new column is selected it checks to see which listthe button was in and removes it, then adds it to the new list. But my new problem is that using lists[i] will no longer work. Idk how to properly loop through my list of arraylists using this declaration:

List<ArrayList<JButton>> lists = new ArrayList<ArrayList<JButton>>(); 
like image 407
mbreen Avatar asked Aug 21 '11 14:08

mbreen


2 Answers

You have to keep a list of lists of JButton objects:

List<List<JButton>> lists = new ArrayList<List<JButton>>();
// populate (replace with your code)
lists.add(Arrays.asList(new JButton("list 1, button 1"), new JButton("list 1, button 2")));
lists.add(Arrays.asList(new JButton("list 2, button 3"), new JButton("list 2, button 4")));
lists.add(Arrays.asList(new JButton("list 3, button 5"), new JButton("list 3, button 6")));
lists.add(Arrays.asList(new JButton("list 4, button 7"), new JButton("list 4, button 8")));

// iterate
for(List<JButton> subList : lists) {
    for(JButton button : subList) {
        System.out.println(button.getText());
    }
}
like image 163
dertkw Avatar answered Sep 21 '22 19:09

dertkw


Giving an example of what worked for me / talked above.

    List []oArrayOfArrayList = new ArrayList[2];

    List<String> oStringList = new ArrayList<String>();
    List<Integer> oIntegerList = new ArrayList<Integer>();

    oArrayOfArrayList[0] = oStringList ;
    oArrayOfArrayList[1] = oIntegerList ;
like image 43
Parasou Avatar answered Sep 21 '22 19:09

Parasou