我们创建一个Set为:

Set myset = new HashSet()

我们如何在Java中创建一个列表?


当前回答

有时候,你可能想要一个新的LinkedList,而不是一个新的ArrayList。从ArrayList开始,如果你有性能问题,并且有证据表明是这个列表出了问题,然后在这个列表上进行大量的添加和删除,然后-不是之前-切换到LinkedList,看看情况是否有所改善。但总的来说,还是用数组列表就好了。

其他回答

就像java中数组列表的声明一样

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

有许多方法可以在java中创建和初始化数组列表。

 1) List list = new ArrayList();

 2) List<type> myList = new ArrayList<>();

 3) List<type> myList = new ArrayList<type>();

 4) Using Utility class

    List<Integer> list = Arrays.asList(8, 4);
    Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

 5) Using static factory method

    List<Integer> immutableList = List.of(1, 2);


 6) Creation and initializing at a time

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});



 Again you can create different types of list. All has their own characteristics

 List a = new ArrayList();
 List b = new LinkedList();
 List c = new Vector(); 
 List d = new Stack(); 
 List e = new CopyOnWriteArrayList();

如果你需要一个单一实体的可序列化的不可变列表,你可以使用:

List<String> singList = Collections.singletonList("stackoverlow");

一个例子:

List somelist = new ArrayList();

您可以查看javadoc for List,并找到包含在java api中的List接口的所有已知实现类。

有很多方法可以创建Set和List。HashSet和ArrayList就是两个例子。现在在集合中使用泛型也相当普遍。我建议你看看它们是什么

这是对java内置集合的一个很好的介绍。http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html

使用谷歌Collections,您可以在Lists类中使用以下方法

import com.google.common.collect.Lists;

// ...

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

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

对于变量参数初始化和从Iterable<T>初始化有重载。

这些方法的优点是,您不需要像使用构造函数那样显式地指定泛型参数——编译器将根据变量的类型推断出它。