Wednesday, November 14, 2007

The trouble with arrays

I've always had trouble with arrays. Either I forget to initialize 'em, or worry about hardcoding the upper limit of values they can take... they're a pain.

names = new String[100]; //why 100? it's a magic number! boo!


So I think it's time to work with dynamic arrays. In Java 5.0 and beyond there is a class called
ArrayList
, which is similar to an array, but has no upper limit (hardcoded, anyways). Plus it's dynamic.

but what if I want to sort my strings? I need them in alphabetical order sometimes.
alphabetical sorts are easy peasy with arrays:

java.util.Arrays.sort(array);

There is no ArrayList.sort() method. Luckily, it's a type of Collection, and Collections do have sort methods.


import java.util.ArrayList;
import java.util.Collections;
...
Collections.sort( myArrayList );

Ta-da!

No comments: