When creating an array, the array is defined by the type you use during instantiation. An array is always an object, there is no such thing as a primitive array. An array can hold both primitives, and reference variables, but not at the same time. With the exception of implicit widening, e.g. putting a byte into an int, Java mandates that an array can only hold objects of their declared type. A major downfall of an array is that you can not change its size, since Java is pass by value, you can create a copy of a portion or all of the array.
Introduce java.util.ArrayList
An ArrayList is by definition a resizable-array implementation of the List interface. Basically, it allows us to have an adjustable array of a declared type. To create a new ArrayList, you must fist import java.util.ArrayList, another option is to type out the full path to ArrayList (java.util.ArrayList) every time you would like to use it.
import java.util.ArrayList;
class ArrayTest {
public static void main (String[] args) {
ArrayList<String> test = new ArrayList<String>();
test.add(”Hello”);
test.add(”Blaggers”);
for (String member : test) {
System.out.println(member);
}
test.remove(1);
for (String member : test) {
System.out.println(member);
}
}
}
By declaring an ArrayList<String>, you’re asking the compiler to guarantee that you only put objects of type into the ArrayList, and by doing so, the compiler can guarantee that any objects removed from the list are of the specified type. The alternative (and I’m not sure how far back you have to go before casting was implemented) would be to create every array (for polymorphism) as a List (because every class extends java.lang.Object in one way or another), and manually cast objects you would like to pull out of it.
Every object pulled from ArrayList (without declaring a type, or any time you use Object (implied here) as a reference type, return type, or parameter type) will be stored in a reference of type Object, even if it’s a dog. You could manually cast it to a dog:
ArrayList listOfObjects = new ArrayList();
Dog foo = new Dog();
listOfObjects.add(foo);
Dog bar = (Dog) listOfObjects.get(0);
But that’s the awesome in the <type> syntax, you’re basically telling
the compiler:
“Hey compiler, make sure I only put objects of type x into this ArrayList, and if I try to trick you, blow up at compile time (instead of run time, a Class Type Casting exception would be bad), oh, and hey, since you’re going to make sure I only add type x, don’t worry about making me manually cast it back to an x when I want to pull an object out if it.”
You can read more about java.util.ArrayList in the Java API. It appears that Wordpress is having troubles displaying the spaces in my code properly. I will attempt to resolve that issue soon.
Tags: Java, Programming