简体   繁体   English

如何创建“N”链接列表?

[英]How to create “N” Linked Lists?

Is it possible to creat n LinkedLists? 是否可以创建n个LinkedLists? I tried this... 我试过这个......

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

I am trying to this in Java. 我在Java中尝试这个。 Any sugestions? 任何sugestions? Thanks 谢谢

Maybe you are coming from C++? 也许你来自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. 在这里您可以找到完整的代码: http//ideone.com/Fv5psb希望这会有所帮助。

You can use ArrayList of LinkedList as follows: ArrayList l = new ArrayList<>(); 您可以使用LinkedList的ArrayList,如下所示:ArrayList l = new ArrayList <>(); You can add n or more LinkedList to this ArrayList. 您可以向此ArrayList添加n个或更多LinkedList。

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. 正如我在评论中提到的,对于嵌套列表结构,不再很好地定义了equalshashcode方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM