how to create a list in java

how to create a list in java

In Java, a list is an ordered collection of elements that can contain duplicate values. There are several ways to create a list in Java.

One way is to use the java.util.ArrayList class, which is an implementation of the List interface that uses an array to store the elements. Here is an example of how you can create an ArrayList and add elements to it:

ref‮t re‬o:lautturi.com
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList of Strings
    ArrayList<String> list = new ArrayList<>();

    // Add elements to the list
    list.add("apple");
    list.add("banana");
    list.add("cherry");

    // Print the list
    System.out.println(list);  // Output: [apple, banana, cherry]
  }
}

This code creates an ArrayList called list that stores elements of type String. It then adds three elements to the list using the add method.

Another way to create a list is to use the java.util.LinkedList class, which is an implementation of the List interface that uses a doubly-linked list to store the elements. Here is an example of how you can create a LinkedList and add elements to it:

import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    // Create a LinkedList of Integers
    LinkedList<Integer> list = new LinkedList<>();

    // Add elements to the list
    list.add(1);
    list.add(2);
    list.add(3);

    // Print the list
    System.out.println(list);  // Output: [1, 2, 3]
  }
}

This code creates a LinkedList called list that stores elements of type Integer. It then adds three elements to the list using the add method.

You can also use the java.util.Arrays.asList method to create a list from an array. Here is an example of how you can do it:

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    // Create an array of strings
    String[]
Created Time:2017-11-01 12:05:16  Author:lautturi