Mastery
Java » Collections

Strings

Immutable objects

Compare using the methods equals and compareTo

The charAt method accesses a character at a given position

Demo of length() and charAt:

String aString = "Hello world!"
System.out.println(aString.length());
System.out.println(aString.charAt(2));

Arrays

Sequence of elements of the same type

Unlike a list, an array’s length is fixed

Index can be any integer expression

Here, the variables ages and names can hold 10 integers and 10 strings, respectively. Each array element in ages has a default value of 0. Each array element in names has a default value of null (as does a new array whose elements are of any reference type).

int[] ages = new int[10];
String[] names = new String[10];

Find the length of an array:

System.out.println(names.length);

More array syntax examples. Click here to view pointer diagrams for second two blocks.

for (String name : names) // Use to reference elements in an array
    System.out.println(name);

int[] x, y, z;
String[] a;
x = new int[3];
y = x;
a = new String[3];
x[1] = 2;
y[1] = 3;
a[1] = "Hello";

int [] q;
q = new int[] { 1, 2, 3 };
// Short form for declarations:
int[] r = { 7, 8, 9 };

Copying Arrays

System.arraycopy() copies numberOfElements elements from the array source, beginning with the element at sourcePosition, to the array destination starting at destinationPosition. The destination array must already exist when System.arraycopy() is called. The source and destination arrays must be of the same type.

System.arraycopy( Object source, int sourcePosition,
                  Object destination, int destinationPosition, int numberOfElements )

// Can write just 'arraycopy' by including at top of file:
import static java.lang.System.*;

Lists

Mutable sequence of 0 or more objects of any type

A generic list constrains its elements to the same supertype

Here, the first list can contain only strings, whereas the second list can contain only instances of class Integer.

List<String> names = new ArrayList<String>();
List<Integer> ages = new LinkedList<Integer>();

Find the length of an array:

System.out.println(names.length);

for (String name: names) // Use to reference elements in an array
    System.out.println(name);