我们创建一个Set为:
Set myset = new HashSet()
我们如何在Java中创建一个列表?
我们创建一个Set为:
Set myset = new HashSet()
我们如何在Java中创建一个列表?
当前回答
列表可以通过多种方式创建:
1 -构造函数初始化
List是一个接口,可以通过以下方式创建List实例:
List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();
2-使用Arrays.asList()
List<Integer> list=Arrays.asList(1, 2, 3);
3-使用Collections类方法
空列表
List<Integer> list = Collections.EMPTY_LIST;
OR
List<Integer> list = Collections.emptyList();
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
无法改变的列表
List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
单例对象列表
List<Integer> list = Collections.singletonList(2);
你可以从下面的参考链接中找到更多的方法。
参考:
https://www.geeksforgeeks.org/initializing-a-list-in-java/
其他回答
List myList = new ArrayList();
或使用泛型(Java 7或更高版本)
List<MyType> myList = new ArrayList<>();
或使用泛型(旧java版本)
List<MyType> myList = new ArrayList<MyType>();
List list = new ArrayList();
或者使用泛型
List<String> list = new ArrayList<String>();
当然,你也可以用任何类型的变量替换字符串,比如Integer。
用Java 8做同样的事情有更多的选择,不是更好,也不是更差,只是不同,如果你想用列表做一些额外的工作,Streams将为你提供更多的选择(过滤,映射,减少等)。
List<String> listA = Stream.of("a", "B", "C").collect(Collectors.toList());
List<Integer> listB = IntStream.range(10, 20).boxed().collect(Collectors.toList());
List<Double> listC = DoubleStream.generate(() -> { return new Random().nextDouble(); }).limit(10).boxed().collect(Collectors.toList());
LinkedList<Integer> listD = Stream.iterate(0, x -> x++).limit(10).collect(Collectors.toCollection(LinkedList::new));
让我总结一下并补充一下:
JDK
1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")
番石榴
1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});
不可变列表
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
空不可变列表
1. Collections.emptyList();
2. Collections.EMPTY_LIST;
字符列表
1. Lists.charactersOf("String") // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
整数列表
Ints.asList(1,2,3); // Guava
List arrList = new ArrayList();
最好按照下面的建议使用泛型:
List<String> arrList = new ArrayList<String>();
arrList.add("one");
如果你使用LinkedList。
List<String> lnkList = new LinkedList<String>();