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?

3 Answers 3

4

Avoid mixing arrays and generics.

Instead, consider this:

List<List<Mp3>> listsList = new ArrayList<List<Mp3>>();
listsList.add(new LinkedList<Mp3>());
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answer! I will try this way.. but it seems instead of shortening my code I will make it longer :D
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.
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.

2 Comments

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 Is the for loop running more then once. You might need to add checks that the list is empty before initializing it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.