Let’s see Comparing ArrayList to a Regular Array,

1. A plain old array has to know its size at the time it’s created

But for ArrayList, you just make an object of type ArrayList. Everytime, it never needs to know how big it should be, because it grows and shrinks as objects are added or removed.

// Size needs to be declared for old array
String[] nameList = new String[10]; 
    
// No need to declare size, although we can give it size if required to
ArrayList<String> nameListNew = new ArrayList<>();

2. To put an object in a regular array, you must assign it to a specific location

An index from 0 to one less than the length of the array is required as below example,

nameList[0] = "Tim";

If the index is outside the boundaries of the array, it throws an exception as below,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

With ArrayList, you can specify an index using the add(anObject) method and the ArrayList will keep growing to make room for the new thing as below,

nameListNew.add("Tim");

3. Arrays use array syntax that’s not used anywhere else in Java

But ArrayList are plain old Java objects, so they have no special syntax. The array brackets [] are special symbol used only for array.

4. ArrayList in Java are parameterized

We just said that unlike arrays, ArrayList have no special syntax.But they do use something special that was added to Java as below,

new ArrayList<String>(); // String type is mentioned as <String>

The type of things which should go in ArrayList can be declared. Parameterized types of ArrayList can be browsed in Collections in Java.

Conclusion

We saw the difference between how the ArrayList and old array varied in usage.

Please follow and like us: