| Adding Elements | ArrayList ⇔ array |
| ArrayIndexOutOfBoundsException | Thread Safety |
| GrowingArrayList | Generics |
| Removing Elements | Learning More |
| Gotchas | Links |
| Trimming |
// 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.
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.
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.
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 an new array, grown or shrunk. Arrays. copyOfRange creates a new array, allowing you to specify the offset in the source.
// making an ArrayList threadsafe ArrayList a = new ArrayList( 100 ); Collection threadSafeList = Collections.synchronizedCollection( a );
| You can get the freshest copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | |
| http://mindprod.com/jgloss/arraylist.html | J:\mindprod\jgloss\arraylist.html | |
![]() | ||
| Canadian Mind Products | ||
| mindprod.com IP:[65.110.21.43] | ||
| view Blog | Your face IP:[38.107.191.104] | |
| Feedback | You are visitor number 133,242. | |