0

What I have is

public static LinkedList<Mp3> musicList;        
...
if (musicList == null) {
    musicList = new LinkedList<Mp3>();
}//create... this works

but if I have like 5 or more lists how can I do something like this:

Object[] ob = new Object[]{musicList,musicList2,...,musicList10};

for (int i = 0; i < ob.length; i++){
    if (ob[i] == null) ob[i] = new LinkedList<Mp3>();
}

If I put it in first way it's working; how can I put it in like in second snippet?

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Hia
  • 103
  • 2
  • 9

3 Answers3

4

Avoid mixing arrays and generics.

Instead, consider this:

List<List<Mp3>> listsList = new ArrayList<List<Mp3>>();
listsList.add(new LinkedList<Mp3>());
MByD
  • 135,866
  • 28
  • 264
  • 277
  • thanks for answer! I will try this way.. but it seems instead of shortening my code I will make it longer :D – Hia Mar 13 '12 at 21:58
  • I ignored the part of how to initialize to make the concept of using only generic collections clearer, it might make it a bit longer, but it will make it better IMHO. – MByD Mar 13 '12 at 21:59
2

Changing the references in the array will not change the original references used to create the array.

The references in the array are a copy of what was in the initialization.

What you should do is get rid of the musicListN variables and only have an array, or better yet use a List.

List<List<Mp3>> musicLists = new ArrayList<List<Mp3>>(LIST_COUNT);
for (int i = 0; i < LIST_COUNT; i++) {
  musicLists.add(new LinkedList<Mp3>());
}

Then use musicLists.get() to everywhere you would have used the older variables.

Michael Krussel
  • 2,586
  • 1
  • 14
  • 16
  • I implemented it in my code, but have 1 more question.. when i init LIST_COUNT = 5, it creates list of 10? so when i look at musicLists.size() it is = 2xLIST_COUNT – Hia Mar 13 '12 at 22:41
  • @Hia Is the for loop running more then once. You might need to add checks that the list is empty before initializing it. – Michael Krussel Mar 14 '12 at 14:17
0

If you really want to do one line object list initialization, look at this Q. Initialization of an ArrayList in one line

Community
  • 1
  • 1
Michael Rice
  • 1,173
  • 5
  • 13