问题
Is it possible to create an array of linked lists? Or an arraylist of linked lists? I've been searching everywhere and seem to be getting contradicting answers. I've seen "no" answers that state that it can't be done because you can't make an array of things that can be dereferenced. I've seen "yes" answers that state it can be done and they end there.
Thanks in advance.
回答1:
If I understand you right, you basicly want to make a 2D Array, but with the second half being a linked list.
import java.util.ArrayList;
import java.util.LinkedList;
public class Test
{
public static void main(String[] args)
{
LinkedList one = new LinkedList();
LinkedList two = new LinkedList();
LinkedList three = new LinkedList();
ArrayList<LinkedList> array = new ArrayList<LinkedList>();
array.add(one);
array.add(two);
array.add(three);
// .. do stuff
}
}
Java doesn't care what the Objects in Arrays or Lists are, so there's nothing against putting another Array or List in.
回答2:
The worst way: creating an array of raw List:
List[] lstString = new List[10];
for(int i = 0; i < lstString.length; i++) {
lstString[i] = new LinkedList<String>();
lstString[i].add(Integer.toString(i));
}
for(int i = 0; i < lstString.length; i++) {
for(Iterator it = lstString[i].iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
}
A slightly better way: use a wrapper class that holds your List and create an array of it:
public class Holder {
List list = new LinkedList();
}
//...
Holder[] holders = new Holder[10];
for(int i = 0; i < holders; i++) {
holders[i] = new Holder();
}
Better approach: use a List<List<Data>>
:
List<List<Data>> lstOfListOfData = new ArrayList<List<Data>>();
for(int i = 0; i < 10; i++) {
lstOfListOfData.add(new LinkedList<Data>());
}
回答3:
I've seen "no" answers that state that it can't be done because you can't make an array of things that can be dereferenced
Doesn't matter if the array's member value is null
, if you still can "access" that member, and instantiate it, it's not dereferenced.
So yes, you can.
来源:https://stackoverflow.com/questions/15193229/can-you-create-an-array-of-linked-lists-in-java