How to create a new list in java

This article was translated from: How to make a new List in Java

We create a Setas: We create a Setas:

Set myset = new HashSet()

WE do the Create A How List? In Java How do we create in Java List?


#1st Floor

Reference: https://stackoom.com/question/3bLw/ How to create a new List in Java


#2nd Floor

The Using Google the Collections , you could use at The following Methods in at The Lists class using Google the Collections , you can Lists using the following methods in the class

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

Overloads are varargs for the Initialization There Initialising and from AN Iterable<T>. Varargs initialization and the Iterable<T>initialization has overloaded.

The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor-the compiler will infer it from the type of the variable. The advantage of these methods is that you do not need to use the constructor Specify the generic parameter explicitly-the compiler will infer it based on the type of the variable.


#3rd floor

List<Object> nameOfList = new ArrayList<Object>();

You need to import Listand ArrayList.


#4th floor

Let me summarize and add something: Let me summarize and add something :

JDK JDK

1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")

Guava Guava

1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

Immutable List unchanging list

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable list

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

List of Characters Character List

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

List of Integers list of integers

Ints.asList(1,2,3);                                             // Guava

#5th Floor

As an option you can use double brace initialization here: As an option, you can use double brace initialization here :

List<String> list = new ArrayList<String>(){
  {
   add("a");
   add("b");
  }
};

#6th floor

List arrList = new ArrayList();

Its better you use generics as suggested below: It better uses generics as suggested below :

List<String> arrList = new ArrayList<String>();

arrList.add("one");

Incase you use LinkedList. If you use LinkedList.

List<String> lnkList = new LinkedList<String>();
Published 0 original articles · praised 8 · 30,000+ views

Guess you like

Origin blog.csdn.net/asdfgh0077/article/details/105490388