user4798789
user4798789

Reputation:

How to create "N" Linked Lists?

Is it possible to creat n LinkedLists? I tried this...

LinkedList l[]= new LinkedList [n] ();

I am trying to this in Java. Any sugestions? Thanks

Upvotes: 1

Views: 135

Answers (3)

Baltasarq
Baltasarq

Reputation: 12202

Maybe you are coming from C++?

You'll have to do that in two steps. First, create the array, and then, create the objects. Your approach is like doing it all in one step.

BTW, it is recommended to put the [] near the type. It clarifies when the type is an array.

    final int n = 2;
    LinkedList<Person>[] l = (LinkedList<Person>[]) new LinkedList[ n ];
    Person[] ps = { new Person( "Daisy" ), new Person( "Donald" ) };

    for(int i = 0; i < l.length; ++i) {
        l[ i ] = new LinkedList<Person>();
    }

    l[ 0 ].add( ps[ 0 ] );
    l[ 0 ].add( ps[ 1 ] );
    l[ 1 ].add( ps[ 0 ] );
    l[ 1 ].add( ps[ 1 ] );

    System.out.println( l[ 0 ] );
    System.out.println( l[ 1 ] );

Here you can find the complete code: http://ideone.com/Fv5psb Hope this helps.

Upvotes: 1

user3248346
user3248346

Reputation:

You can do this:

    // Create your nested list structure
    List<LinkedList<Integer>> n = new ArrayList<>();

    // Create your linked lists
    LinkedList<Integer> ll1 = new LinkedList<>();
    ll1.add(1);
    ll1.add(2);

    LinkedList<Integer> ll2 = new LinkedList<>();
    ll2.add(1);
    ll2.add(2);

    // add your linked lists to the nested list structure
    n.add(ll1);
    n.add(ll2);

    // print out the data
    for(LinkedList<Integer> l : n){
        for(Integer i : l){
            System.out.println(i);
        }
    }

Output

1
2
1
2

As I mentioned in the comment, the equals and hashcode methods are no longer well defined for nested list structures.

Upvotes: 1

Abhishek Kumar
Abhishek Kumar

Reputation: 11

You can use ArrayList of LinkedList as follows: ArrayList l = new ArrayList<>(); You can add n or more LinkedList to this ArrayList.

Upvotes: 1

Related Questions