Linked list of linked lists in Java

I would like to know how to create a linked list of linked lists. It would also be useful if the predefined LinkedList (a class from Java) and its methods are used to define add, get, listIterating and other operations.

+6
source share
4 answers

You can put any object in the list, including another list.

 LinkedList<LinkedList<YourClass>> list = new LinkedList<LinkedList<YourClass>>(); 

is a LinkedList object of a LinkedList object of YourClass . It can also be written in a simplified way with Java 7 :

 LinkedList<LinkedList<YourClass>> list = new LinkedList<>(); 

Very simple examples of manipulating such a list:

Then you need to create each sublister by adding one subscription:

 list.add(new LinkedList<YourClass>()); 

Then create content objects:

 list.get(sublistIndex).add(new YourClass()); 

Then you can iterate over it this way (subscription items are grouped by subscription):

 for(LinkedList<YourClass> sublist : list) { for(YourClass o : sublist) { // your code here } } 

If you want to add specific methods to this list of lists, you can create a subclass from LinkedList (or List or any other subclasses of List ), or you can create a class with a list of lists as a field and add methods to manage the list.

+21
source

Well, I made this code, and it worked out for me.

  java.util.LinkedList mainlist = new java.util.LinkedList(); java.util.LinkedList sublist1 = new java.util.LinkedList(); sublist1.add(object1); sublist1.add(object2); sublist1.add(object3); java.util.LinkedList sublist2=new java.util.LinkedList(); sublist2.add(1); sublist2.add(2); mainlist.add(sublist1); mainlist.add(sublist2); // To retrieve the sublist1 from mainlist........... java.util.LinkedList temp = (java.util.LinkedList)mainlist.get(0); 

Here the mainlist variable LinkedList of the LinkedLists links , and the temp variable contains the value that is stored in the first list, i.e. sublist1 ..

+2
source

You can even simplify access to secondary lists, for example. using

  final List<List<String>> lists = new LinkedList<List<String>>() { @Override public List<String> get(final int index) { while (index >= size()) { add(new LinkedList<>()); } return super.get(index); } }; 

This code automatically adds the new LinkedList to the external list. With this code, you can easily add individual values:

 lists.get(2).add("Foo"); 
+1
source
 LinkedList<LinkedList<YourClass>> yourList = new LinkedList<LinkedList<YourClass>>(); 

Like an ad. To add another linked list (to the end by default), you should do

 yourList.add(new LinkedList<YourClass>()); 

To add an item, we can say that the second linked list from the series:

 yourList.get(1).add(new YourClass()); 
0
source

Source: https://habr.com/ru/post/918173/


All Articles