-6

I'm trying to create a large number of sub linked lists within a list so they should look something like this:

[[sublist1,[sublist2],...,[sublist32]]

I keep getting an error when trying to use this code and I can't seem to know why.

public class Lists {

    static public void main(String[] args) {
        LinkedList <Integer>[] LK=new LinkedList [100];
        for (int i=0;i<2;i++){
            LK[i].add(i+1);
        }
        System.out.println(LK);
    }
}
Alex K
  • 22,315
  • 19
  • 108
  • 236
  • 1
    Your syntax is wrong in the `LK` declaration. In the future, post the error itself as well. – Kon Jul 05 '16 at 21:25
  • Exception in thread "main" java.lang.NullPointerException at h3h3.main(Lists.java:9) – CreativeName Jul 05 '16 at 21:35
  • 1
    You need to actually instantiate each instance within the array. – copeg Jul 05 '16 at 21:37
  • See [this](http://stackoverflow.com/questions/30301489/trying-to-build-an-array-of-objects-but-getting-a-nullpointer-exception) and [this](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – copeg Jul 05 '16 at 21:40

1 Answers1

0

Your linked list declaration is wrong. You don't use [] when creating a new object in java. Instead you use (). And your generic type is also wrong -> if you want to have more linked lists inside the main linked list.

Try this

LinkedList<LinkedList> LK = new LinkedList<>();

Note - The part inside <> tells what kind of object are you going to put inside the Linked List. You want to put linked lists inside your main linked list. So it should be LinkedList class. This is called java generics.

To add 256 sub linked lists,

for(int i = 0; i < 256; i++){
    LinkedList l = new LinkedList();
    LK.add(l);
}

Note that this adds 256 empty linked lists to the main linked list. I didn't use the generic form with the above 256 linked lists.

What you have stated in your question was that you want to add sub linked lists to a list. But what you have tried to do was adding them to array. Since you seem a bit confused about the syntax I recommand you look up the following topics.

  • Java declaring and initializing arrays
  • Declaring and initializing objects
  • Linked lists vs arrays
  • Generics
Ivantha
  • 491
  • 2
  • 9
  • 27
  • Thanks for the help and advice, but could you also tell me how I could create a large number of sub linked lists at once, since I'm trying to create 256 sub linked lists.. – CreativeName Jul 06 '16 at 06:48
  • Use a for loop to create and add sub linked lists to main list. Should I clarify more? – Ivantha Jul 06 '16 at 06:52
  • That would be really helpful, excuse me if I seem a bit lost, it's just that our tutor told us to use LinkedList [] lk =new LinkedList [x]; and lk[i].add(x); That's why I cant seem to have any further progress Thanks for your help! – CreativeName Jul 06 '16 at 07:01