Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked List of Linked Lists in Java

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

like image 610
Anand Kumar Avatar asked Jun 15 '12 12:06

Anand Kumar


1 Answers

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

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

is a LinkedList of LinkedLists of YourClass objects. It can also be written in a simplified way since Java 7:

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

Very simple examples of manipulating such a list:

You then need to create each sublist, here adding a single sublist:

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

Then create the content objects:

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

You can then iterate over it like this (sublists' items are grouped by sublist):

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 of LinkedList (or List, or any other List subclasses) or you can create a class with the list of lists as a field and add methods there to manipulate the list.

like image 60
Autar Avatar answered Oct 03 '22 17:10

Autar