1 ARRAYS
An array is a data structure that stores a collection of values of the same type.
1.1 Declaring an array
Arrays are declared using the [] index operator for example:
int[] integerArray;
double[] doubleArray;
Employee[] employeeArray;
Day[] dayArray;
Note that the declaration does not construct the array or allocate storage space. Array
elements can only be accessed after the array has been constructed.
1.2 Constructing arrays
To construct an array use the “new” operator because arrays are objects:
new Employee[1000];
new int[23];
new double[45];
new Day[2345];
new String [234];
the above are examples of anonymous objects.
The size of the array should always be specified otherwise you get a syntax error.
1.3 Defining arrays
Arrays are constructed by combining the declaration and the construction:
int[] intArray = new int[23];
Day[] dayArray = new Day[23];
Employee[] empArray = new Employee[67];
1.4 Initialisation for arrays
Array elements are initialized using the normal convention, zero for numbers, false for
booleans and null for objects. Arrays can be explicitly initialised during the construction
of objects:
Prepared by Zanamwe N
double[] doubleArray = new double[] {1.3, 34.6, 45.67, 23.4567, 7.0};
// don’t specify the array size
there is also a short hand assignment method:
double[] doubleArray = {1.3, 34.6, 45.67, 23.4567, 7.0};
1.5 Referencing array elements
To reference array elements use the array indexing operator []. Note that the first element of
arrays is index zero. The number of array elements is provided in the array instance
variable “length”:
int[] intArray = new int[23];
for (int i = 0; i <= [Link]; i++)
{
[Link](intArray[i]);
}
This instance variable is different from the length() method of the String Class.
1.6 The for each loop
The basic for loop was extended in Java 5 to make iteration over arrays and other collections
more convenient. This newer for statement is called the enhanced for or foreach (because it
is called this in other programming languages). I've also heard it called the for-in loop.
Use it in preference to the standard for loop if applicable because it's much more readable.
Series of values. The for-each loop is used to access each successive value in a collection
of values.
Arrays and Collections. It's commonly used to iterate over an array or a Collections class
(eg, ArrayList).
Iterable<E>. It can also iterate over anything that implements the Iterable<E> interface
(must define iterator() method). Many of the Collections classes (eg, ArrayList) implement
Iterable<E>, which makes the for-each loop very useful. You can also implement
Iterable<E> for your own data structures.
This is a looping construct that allows you to loop thru each element in an array without
having to fuss with loop control variables.
for (collection element : collection)
{ statement
}
Prepared by Zanamwe N
Note that the element should be the same as the type of array or collection. When you see
the colon (:) read it as “in.” The loop above reads as “for each collection element in
collection.”
for (int value : intArray)
{
[Link](value);
}
The for each loop sets the given variable to each element of the collection and then execute
the statement.
Example:
Day[] da = {new Day(2009,10,12), new Day(2013,6,12), new Day(2012,12,23)};
for(Day iterator: da)
{
[Link](iterator);
}
Note that attempts to reference an array element outside the index bounds zero to length
generates an ArrayIndexOutOfBoundsException at run time not at compile time.
1.7 Copying arrays.
Arrays are objects and assigning array variables assigns references.
int[] ib = {1,3,6,7,8,9};
int[] ia = ib; ib[2]++; // now element ib[2] has been incremented!
Since arrays are mutable, assignment is unsafe. Instead use the clone() method:
int[] ia = (int[])[Link]();
The array clone method returns type Object so it must be cast to int[].
To assign array elements between or within arrays use the:
[Link](fromarray, fromstart, toarray, tostart, count);
Prepared by Zanamwe N
For example:
[Link](ia, i, ia, i-1, [Link]-1); copies the elements from index i,
effectively moving down the elements and removing element i.
Example 2
int[] ia = {23, 45, 50, 23, 56};
int[] ib = new int[3];
[Link](ia,1,ib,0,3);
1.8 Dynamic construction
Arrays are constructed dynamically at runtime. If additional array elements are required, a
new larger array may be constructed, the original array elements copied and the new array
assigned to the original one:
int[] termp = new int[[Link]*2];
temp = ia;
the space allocated to the original array is recycled by the garbage collector.
1.9 Multidimensional arrays
Multidimensional arrays are declared using as many [] index operators as necessary. For
example:
final int ROWS = 4;
final int COLS = 12;
int[][] matrix2D = new int[ROWS][COLS];
final int PLANES = 3;
int[][][] matrix3D = new int[ROWS][COLS][PLANES];
example of a 2D Array
int[][] smallArray = { { 10, 11, 12, 13 }, { 20, 21, 22, 23 },
{ 30, 31, 32, 33 }, { 40, 41, 42, 43 }, };
or can initialiase it as:
smallArray[0][0] =10;
smallArray[0][1] =11;
smallArray[0][2] =12;
smallArray[0][0] =13;
Prepared by Zanamwe N
smallArray[1][0] =20;
2 ArrayLists
The class ArrayList provides an array-like structure, which provides automatic dynamic
sizing and many useful methods. The elements in an ArrayList are of class Object. The
class is in the [Link] package.
The ArrayList class extends AbstractList and implements the List interface. ArrayList
supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed
length. After arrays are created, they cannot grow or shrink, which means that you must
know in advance how many elements an array will hold. But, sometimes, you may not know
until run time precisely how large of an array you need. To handle this situation, the
collections framework defines ArrayList. In essence, an ArrayList is a variablelength
array of object references. That is, an ArrayList can dynamically increase or decrease in
size. Array lists are created with an initial size. When this size is exceeded, the collection is
automatically enlarged. When objects are removed, the array may be shrunk.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list
that is initialized with the elements of the collection c. The third constructor builds an array
list that has the specified initial capacity. The capacity is the size of the underlying array that
is used to store the elements. The capacity grows automatically as elements are added to an
array list.
The following program shows a simple use of ArrayList. An array list is created, and then
objects of type String are added to it. (Recall that a quoted string is translated into a String
object.) The list is then displayed. Some of the elements are removed and the list is
displayed again.
ArrayList<Data type> al = new ArrayList <Data type>();
Eg
ArrayList<String> al = new ArrayList<String>();
Prepared by Zanamwe N
2.1 Methods in the ArrayList Class
1. add(object); this adds an element to an ArrayList, by default the add() method
appends the element to the end of the list. To insert the element at a specific position
use the add(i, object):
[Link](0, new String(“tom musa”)); this inserts the new object at position 0 and
moves the remaining elements up.
2. set(i, object); this method overwrites an element at a particular position:
[Link](1, new String(“zacks jim”));
3. remove(i); this removes a particular element from the ArrayList [Link](2);
4. size(); this returns the number of elements in an ArrayList [Link]();
5. get(i); this is used to access elements in an ArrayList. This method returns an object
which needs to be cast:
String s1 = (String)[Link](1);
Numbers are not objects in Java so they cannot be directly stored in an ArrayList. Use the
wrapper classes:
double x = 3.678;
Double wrapper = new Double(x);
[Link](wrapper);
to retrieve the original value from the wrapper use the value() methods:
Double wrapper = (Double)[Link](3);
double x = [Link]();
Prepared by Zanamwe N