Java Vector or ArrayList for Primitives

后端 未结 5 2247
滥情空心
滥情空心 2020-12-09 03:35

Is there an expandable array class in the Java API equivalent to the Vector or ArrayList class that can be used with primitives (int, char, double,

相关标签:
5条回答
  • 2020-12-09 03:52

    http://trove4j.sourceforge.net/

    The Trove library provides high speed regular and primitive collections for Java.

    Note that because Trove uses primitives, the types it defines do not implement the java.util collections interfaces.

    (LGPL license)

    0 讨论(0)
  • 2020-12-09 03:54

    There is unfortunately no such class, at least in the Java API. There is the Primitive Collections for Java 3rd-party product.

    It's pretty dangerous to use auto-boxing together with existing collection classes (in particular List implementations). For example:

    List<Integer> l = new ArrayList<Integer>();
    l.add(4);
    
    l.remove(4); //will throw ArrayIndexOutOfBoundsException
    l.remove(new Integer(4)); //what you probably intended!
    

    And it is also a common source of mysterious NullPointerExceptions accessing (perhaps via a Map):

    Map<String, Integer> m = new HashMap<String, Integer>();
    m.put("Hello", 5);
    int i = m.get("Helo Misspelt"); //will throw a NullPointerException
    
    0 讨论(0)
  • 2020-12-09 03:54

    Modern Java supports autoboxing of primitives, so you can say

    List<Integer> lst = new ArrayList<Integer>;
    lst.add(42);
    

    That at least avoids the syntactic vinegar of new Integer(42).

    0 讨论(0)
  • 2020-12-09 03:58

    Eclipse Collections has primitive ArrayLists for all primitive types, as well as primitive Sets, Bags, Stacks and Maps. There are immutable versions of all of the primitive container types as well.

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
  • 2020-12-09 04:01

    Joda-Primitives.

    There is also Primitive Collections for Java but it's a bit out of date.

    0 讨论(0)
提交回复
热议问题