[英]array of objects proper way of use?
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: 但是如果我有5个或更多的列表,该如何做:
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?
我怎样才能像第二个片段一样?
Avoid mixing arrays and generics. 避免混合使用数组和泛型。
Instead, consider this: 而是考虑一下:
List<List<Mp3>> listsList = new ArrayList<List<Mp3>>();
listsList.add(new LinkedList<Mp3>());
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. 您应该做的是摆脱musicListN变量,而只拥有一个数组,或者最好使用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. 然后,将musicLists.get()应用于所有使用较旧变量的地方。
如果您确实要进行一行对象列表的初始化,请看此问题。 一行中的ArrayList的初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.