How to make a new List in Java
We create a Set
as:
Set myset = new HashSet()
How do we create a List
in Java?
List myList = new ArrayList();
or with generics (Java 8 or later)
List<MyType> myList = new ArrayList<>();
or with generics (Old java versions)
List<MyType> myList = new ArrayList<MyType>();
另外,如果你想创建一个包含事物的列表(虽然它将是固定的大小):
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
Let me summarize and add something:
JDK
1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")
Guava
1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});
Immutable 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
1. Lists.charactersOf("String") // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
List of Integers
Ints.asList(1,2,3); // Guava
链接地址: http://www.djcxy.com/p/19956.html
上一篇: 为什么在Java 8接口方法中不允许“final”?
下一篇: 如何在Java中创建一个新的List