lacas
lacas

Reputation: 14066

Java /Android what is faster than ArrayList?

What is faster than ArrayList<String> in Java ? I have a list which is of an undefined length. (sometimes 4 items, sometimes 100).

What is the FASTEST way to add and get it from any list ? arrayList.add(string) and get() are very slow.

Is there a better way for this? (string s[] and then copyArray are the slowest?)

Upvotes: 1

Views: 4241

Answers (6)

ElJeffe
ElJeffe

Reputation: 677

Take a look the Jodd Utilities. They have some collections that implement ArrayList but on primatives (jodd/util/collection/), such as IntArrayList. So if you're creating a ArrayList of int, float, double, etc.. it will be faster and consume less memory.

Even faster than that is what they call a FastBuffer, which excels at add() and can provide a get() at O(1).

The classes have little interdependency, so it's easy to just drop in the class you need into your code.

Upvotes: 1

Ken
Ken

Reputation: 31161

100 items is not very many. Your bottleneck is elsewhere.

Upvotes: 2

segfault
segfault

Reputation: 5939

Both add() to end of list and get() should run in O(1). And since length is undefined, you can't use a fixed length array. You can't do any better I'm afraid.

add(int index, E element) takes linear time for worst case though if that's why you think it's slow. If that is the case, either use Hashtable (insertion takes constant time) or TreeMap (insertion takes logarithmic time).

Upvotes: 2

Dawid Sajdak
Dawid Sajdak

Reputation: 3084

You can use javolution library. http://javolution.org

http://javolution.org/target/site/apidocs/javolution/util/FastList.html

ist much faster than arraylist ;)

Upvotes: 0

duffymo
duffymo

Reputation: 308743

Faster for what?

"basically arraylist.add(string) and get() is very slow." - based on what evidence? And compared to what? (No need for the word 'basically' here - it's a high tech "um".) I doubt that ArrayList is the issue with your app. Profiling your code is the only way to tell whether or not you're just guessing and grasping at straws.

Even an algorithm that's O(n^2) is likely to be adequate if the data set is small.

You have to understand the Big-Oh behavior of different data structures to answer this question. Adding to the end of an ArrayList is pretty fast, unless you have to resize it. Adding in the middle may take longer.

LinkedList will be faster to add in the middle, but you'll have to iterate to get to a particular element.

Upvotes: 5

curiousity
curiousity

Reputation: 4741

Try to use hashtable it is much faster

Upvotes: -5

Related Questions