How to create an array of linked lists in java?

Java 8Object Oriented ProgrammingProgramming

A linked list is a sequence of data structures, which are connected together via links.

To create an array of linked lists, create required linked lists and, create an array of objects with them.

Example

Live Demo

import java.util.LinkedList;

public class ArrayOfLinkedList {
   public static void main(String args[]) {
      LinkedList list1 = new LinkedList();
      list1.add("JavaFX");
      list1.add("Hbase");
     
      LinkedList list2 = new LinkedList();
      list2.add("OpenCV");
      list2.add("Mahout");
     
      LinkedList list3 = new LinkedList();
      list3.add("WebGL");
      list3.add("CoffeeScript");
      Object[] obj = {list1, list2, list3};
     
      for (int i=0; i<obj.length; i++) {
         System.out.println(obj[i].toString());
      }
   }
}

Output

[JavaFX, Hbase]
[OpenCV, Mahout]
[WebGL, CoffeeScript]

You can also create Array list of linked lists as –

Example

Live Demo

import java.util.ArrayList;
import java.util.LinkedList;

public class ArrayOfLinkedList {
   public static void main(String args[]) {
      LinkedList list1 = new LinkedList();
      list1.add("JavaFX");
      list1.add("Hbase");
     
      LinkedList list2 = new LinkedList();
      list2.add("OpenCV");
      list2.add("Mahout");
     
      LinkedList list3 = new LinkedList();
      list3.add("WebGL");
      list3.add("CoffeeScript");
     
      ArrayList <LinkedList> aList = new ArrayList<LinkedList>();
      aList.add(list1);
      aList.add(list2);
      aList.add(list1);
      System.out.println(aList);
   }
}

Output

[[JavaFX, Hbase], [OpenCV, Mahout], [JavaFX, Hbase]]
raja
Published on 09-Feb-2018 11:20:19
Advertisements