ArrayList : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

ArrayList

ArrayList is like Vector without the synchronisation overhead. In Java version 1.1 ArrayList is about 3-4 times faster than Vector, though with JDK (Java Development Kit) 1.1.4+ the difference is not so pronounced. (Rolling your own array is about 40 times faster than Vector.) For compatibility with versions of Java prior to  Java version 1.1, you need to use Vector instead. Don’t use Vector in new code. It has confusing redundant methods and the synchronisation is excessive and implicit.

You can check if a List is in order with com.mindprod.common18.InOrder.

Adding Elements ArrayList ⇔ array
ArrayIndexOutOfBoundsException Arrays.asList
GrowingArrayList Thread Safety
Removing Elements Generics
contains Learning More
Gotchas Links
Trimming

Adding Elements to An ArrayList

// adding an element to the middle of a list
arrayList.add( i, object );

// adding an element to the end of a list
arrayList.add( object );

actually inserts, sliding existing elements up to make room. As you might guess, this is an expensive operation when there are many elements.

ArrayIndexOutOfBoundsException

ArrayList will often give you ArrayIndexOutOfBoundsException or IndexOutOfBoundsException. There are many ways to generate one.

GrowingArrayList

Unlike an array where you get the size with v.length, with an ArrayList you use v. size();

With an ordinary ArrayList you can’t set elements until you have grown the ArrayList sufficiently first with add. If you try it, you will get an ArrayIndexOutOfBoundsException or IndexOutOfBoundsException.

If you want an ArrayList that grows automatically when you use a set index too big, here is the complete source code for it.

Ordinary ArrayList has no setSize or setLength method. You cannot grow the list by more than one element at a time.

Removing Elements From An ArrayList

If you have an Iterator running, you must use Iterator.remove, not ArrayList.remove.

ArrayList.clear sets each of the elements to null, then sets the size to 0 However, it does not reallocate the array.

Trimming ArrayLists

When you are done removing elements, you have logically removed them, but the RAM (Random Access Memory) they had allocated is still nailed down, ready to use for future growth. If you want to reclaim it, you must use ArrayList. trimToSize(), which allocates a new internal array just the right size and copies everything over from the new one, and discards the old one to be later garbage collected. You don’t normally want to use trimToSize unless you know the ArrayList is not going to grow again, any time soon. It is a relatively costly operation, so you don’t want to do it just to reclaim a handful of bytes. You might use it after a massive pruning, or after you were sure nothing new was coming.

When I am absolutely sure there are no new elements coming for the ArrayList, I typically use toArray and use the much faster raw array from then on. I think of ArrayLists mainly as tools to build a Collections and I think of arrays as tools to process them. However, most other programmers are not nearly so keen as I am on naked arrays. They prefer to do everything with ArrayLists. when you use generics and for:each it is relatively easy to flip back and forth between each style.

ArrayList.add or ArrayList. addAll will not discard duplicates. To do that you would need to check with  ArrayList.contains before adding, or create a HashSet which naturally dedups, then use ArrayList. addAll to effectively convert it to an ArrayList.

ArrayList.contains could have plausibly been implemented two different ways, to compare with equals or with ==. It uses equals and a linear search.

ArrayList.contains

ArrayList.contains serially searches an ArrayList for a match. It uses equals, not equalsIgnoreCase. That means Strings in an ArrayList need not be interned. It also means you can use contains on an ArrayList of Longs or other Objects with a suitable equals method.

Gotchas

ArrayList ⇔ array

More complex conversions can be handled by combining ArrayList. toArray, List.subList, Arrays.copyOf, Arrays. copyOfRange and System. arraycopy. subList does not make a copy. Any changes to the sublist are reflected in the original. System.arraycopy is quite general letting you pick the offset in both the source and destination. Arrays. copyOf creates a new array, grown or shrunk. Arrays. copyOfRange creates a new array, allowing you to specify the offset in the source.

Arrays.asList

I wrote a method of the form:

String[] someMethod( ... )

IntelliJ complained this was a wicked thing to do. Why? Because the caller could modify the String array and it would wreck my copy inside someMethod. So what do people do? They use Arrays.asList to convert to a List, (it turns out a java.util.Arrays.ArrayList). But the List still lets the user modify the fields which in turn modify the underlying array. We have gained nothing.

We also have to use Collections.unmodifiableList which gives us a java.util.Collections.UnmodifiableRandomAccessList wrapper around our List that throws a UnsupportedOperationException when we attempt to write.

The catch is the set methods are still there. We don’t find out about the problem of their use modifying this List until run time.

I hope it is obvious, but as Leif Roar Moldskred pointed out the problem isn’t that you’re returning something the client can modify. The problem is that you’re giving the client backdoor access into this object’s private state: if you just return your internal array any changes the client does to that array are a change in the state of this. If you return a copy of the internal array, or a list created from the internal array, any changes made to the return value by the client only affects the client’s state, not thiss. So an alternative way to handle this is to return a clone of the array.

asList returns a List object, but it is actually a modifiable ArrayList.

Thread Safety of ArrayLists

To get the thread safety of Vector in ArrayList wrap it like this:

// making an ArrayList threadsafe
ArrayList a = new ArrayList( 100 );
Collection threadSafeList = Collections.synchronizedCollection( a );

Generics with ArrayLists

Using an ArrayList with generics:

Learning More

Oracle’s Javadoc on ArrayList class : available:
Oracle’s Javadoc on ArrayList.set : available:
Oracle’s Javadoc on Arrays class : available:
Oracle’s Javadoc on Collections.emptyList : available:
Oracle’s Javadoc on Collections.sort (Lists only) : available:
Oracle’s Javadoc on ArrayList.sort : available:
Oracle’s Javadoc on Collections.synchronizedList : available:
Oracle’s Javadoc on Collections.unmodifiableList : available:
Oracle’s Javadoc on ArrayList.toArray : available:
Oracle’s Javadoc on List.subList : available:
Oracle’s Javadoc on Arrays.copyOf : available:
Oracle’s Javadoc on Arrays.copyOfRange : available:
Oracle’s Javadoc on System.arraycopy : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/arraylist.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\arraylist.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[3.15.0.46]
You are visitor number