0

I want to create an array of pointers to linked lists and then go through each list. To create it can I simply create however many lists I need and then just do something like

LinkedList array[] = new LinkedList[length];

and then just set a loop to set each value in the array to point to one of the lists?

How would I go through each list after I set it all up? I thought it was something like

while(array[x].hasNext()){
    //do stuff
    x++;
}
Joel
  • 4,732
  • 9
  • 39
  • 54

2 Answers2

0

You have mixed up Java array objects and the collection framework's List api. You can do what you want in a couple of ways:

  1. Using arrays (highly discouraged—see this thread):

    LinkedList array[] = new LinkedList[length];
    
    ...
    
    for (int i = 0; i < array.length; ++i) {
        LinkedList list = array[i];
        // do stuff with list
    }
    
  2. Using a List:

    List<LinkedList> array = new ArrayList<LinkedList>();
    
    ...
    
    for (Iterator<LinkedList> iter = array.iterator();
         iter.hasNext();
        )
    {
        LinkedList list = iter.next();
        // do stuff with list
    }
    

In both cases, you might benefit from using an enhanced for loop:

for (LinkedList list : array) {
    // do stuff with list
}

This works for either the array-based or List-based versions.

P.S. You should not be using raw LinkedList types. Instead, you should bind the generic type parameter of LinkedList to a specific element type (even if it's Object). For example:

List<LinkedList<String>> array = new ArrayList<LinkedList<String>>();

The language allows raw types for the sake of old code, but new code should never use them. However, the first option above will not work—you will have to use the second approach.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

your while loop is incorrect:

Just do something like this!

for (LinkedList list : array) {
    for (Item object : list) {
        // Do something here with the item
    }
}

btw you should not use LinkedList without a type, use one of the following

LinkedList<String> or 
LinkedList<WhateverObjectYouLike> or 
LinkedList<? extends whatEverObjectYouLike>

so lets say you want to create an array of 10 lists and every list should contain strings.

LinkedList<String> array[] = new LinkedList<String>[10];
for (int i=0; i<10; i++) {
    array[i] = new LinkedList<String>();
}

// Add some strings to each list, as you like
...

// Print all added Strings:
for (LinkedList<String> list : array) {
    for (String item : list) {
        System.out.println(item);
    }
}
Michael
  • 815
  • 1
  • 6
  • 23