Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Vector or ArrayList for Primitives

Tags:

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, etc)?

I need a quick, expandable array for integers and it seems wasteful to have to wrap them in the Integer class in order to use them with Vector or ArrayList. My google-fu is failing me.

like image 527
Daniel Bingham Avatar asked Aug 19 '09 17:08

Daniel Bingham


People also ask

Can you have an ArrayList of primitives?

Primitive data types cannot be stored in ArrayList but can be in Array.

Which is better ArrayList or Vector in Java?

Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.

Why ArrayList Cannot use primitives?

ArrayList accepts only reference types as its element, not primitive datatypes. When trying to do so it produces a compile time error.

Is Vector outdated in Java?

Vector class is often considered as obsolete or “Due for Deprecation” by many experienced Java developers. They always recommend and advise not to use Vector class in your code. They prefer using ArrayList over Vector class.


2 Answers

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 
like image 175
oxbow_lakes Avatar answered Dec 29 '22 23:12

oxbow_lakes


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)

like image 41
skaffman Avatar answered Dec 30 '22 01:12

skaffman