Oop - 5
Oop - 5
PROGRAMMING
YSS#
ed.). Addison-Wesley.
ARRAYS & COLLECTIONS
Arrays
-> Array is the most commonly used data storage structure; it’s built into most programming languages
Example: You want to keep track of the marks for top 10 students; store them in an array of 10 elements
instead of declaring 10 variables to hold each of the values. -
> Marks for all the 10 students are of the same type , say float or int
The following figure illustrate an array of marks for 10 Students, notice that each position is indexed
starting at index 0. Arrays use zero-based indexes; meaning position 1 is index 0 and similarly position 10
is index 9
39 78 76 43 12 95 34 21 54 28
Assuming the name of the array is marksArray, then to access the item at position 3; we use
marksArray[2] and to access value at position 10 we use marksArray[9]
Such an organization is quite useful, for it allows us to do some interesting computations. For example, the following
method adds up all the numbers in an array of integers:
This example takes advantage of a nice feature of Java, which allows us to find the number of cells an array stores, that is,
its length. In Java, an array a is a special kind of object and the length of a is stored in an instance variable, length.
That is, we never need to guess the length of an array in Java, the length of an array can be accessed as follows:
array_name.length
where array_name is the name of the array. Thus, the cells of an array a are numbered 0, 1,2, and so on,
up to a.length − 1.
Array Elements and Capacities
Each object stored in an array is called an element of that array. Element number 0 is a[0], element number 1
is a[1], element number 2 is a[2], and so on. Since the length of an array determines the maximum number of
things that can be stored in the array, we will sometimes refer to the length of an array as its capacity. We
show another simple use of an array in the following code fragment, which counts the number of times a
certain number appears in an array:
/** Counts the number of times an integer appears in an array. */
public static int findCount(int[] a, int k) {
int count = 0;
foreach (int e: a) { // note the use of the "foreach" loop
if (e == k) // check if the current element equals k
count++;
}
return count;
}
Out of Bounds Errors
It is Fatal to access an array out of its ranges; this will always result in unpleasant errors.
It is a dangerous mistake to attempt to index into an array a using a number outside the range from 0
to a.length - 1. Such a reference is said to be out of bounds. Such attempted access results in
ArrayIndexOutOfBoundsException Error
Creating / Declaring Arrays
NB: Arrays have a length field, which you can use to find the size (the number of elements) of an array:
int arrayLength = intArray.length; // find array size
Array Example 1
Int [] b =a;
An illustration of an assignment of array objects. We show the result of setting "b[3] = 5;" after previously
setting "b = a;".
Array Example 2
// array.java
// demonstrates Java arrays
// to run this program: C>java arrayApp
////////////////////////////////////////////////////////////////
class ArrayApp
{
public static void main(String[] args)
{
long[] arr; // reference to array
arr = new long[100]; // make array
int nElems = 0; // number of items
The Basics of Arrays in Java 41
int j; // loop counter
long searchKey; // key of item to search for
//--------------------------------------------------------------
arr[0] = 77; // insert 10 items
arr[1] = 99; arr[2] = 44;arr[3] = 55;arr[4] = 22;arr[5] = 88; arr[6] = 11;arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // now 10 items in array
//--------------------------------------------------------------
for(j=0; j<nElems; j++) // display items
System.out.print(arr[j] + “ “);
System.out.println(“”);
//--------------------------------------------------------------
searchKey = 66; // find item with key 66
for(j=0; j<nElems; j++) // for each element,
if(arr[j] == searchKey) // found item?
break; // yes, exit before end
if(j == nElems) // at the end?
System.out.println(“Can’t find “ + searchKey); // yes
else
System.out.println(“Found “ + searchKey); // no
//--------------------------------------------------------------
searchKey = 55; // delete item with key 55
for(j=0; j<nElems; j++) // look for it
if(arr[j] == searchKey)
break;
for(int k=j; k<nElems-1; k++) // move higher ones down
arr[k] = arr[k+1];
nElems--; // decrement size
//--------------------------------------------------------------
for(j=0; j<nElems; j++) // display items
System.out.print( arr[j] + “ “);
System.out.println(“”);
} // end main()
} // end class ArrayApp
In this program, we create an array called arr, place 10 data items in it, search for the item with value 66, display all the
items, remove the item with value 55 and then display the remaining 9 items.
Insertion
Inserting an item into the array is easy; we use the normal array syntax:
arr[0] = 77;
Searching
The searchKey variable holds the value we’re looking for. To search for an item, we step through the array, comparing
searchKey with each element. If the loop variable j reaches the last occupied cell with no match being found, the value isn’t in
the array. Appropriate messages are displayed e.g: Found 66 or Can’t find 27.
Deletion
Deletion begins with a search for the specified item. For simplicity, we assume that the item is present. When we find it, we
move all the items with higher index values down one element to fill in the “hole” left by the deleted element, and we
decrement nElems.
NB: In a real program, we would also take appropriate action if the item to be deleted could not be found.
Display
Displaying all the elements is straightforward: We step through the array, accessing each one with arr[ j] and displaying it.
Cloning an Array
If instead, we wanted to create an exact copy of the array, a, and assign that array to the array variable, b, we should write
b = a.clone();
An illustration of cloning of array objects. We show the result of setting "b[3] = 5;" after previously setting
"b = a.clone();".
COLLECTIONS
Collection
Type Implementation
Deque ArrayDeque
List
partList.add(new Integer(1111));
partList.add(new Integer(2222));
partList.add(new Integer(3333));
partList.add("Bad Data"); // compiler error now
The main difference between List and Set in Java is that List is an ordered collection, which
allows duplicates, whereas Set is an unordered collection, which does not allow duplicates.
TreeSet: Implementation of Set
set.add("one");
set.add("two");
set.add("three");
set.add("three"); // not added, only unique
•Hashtable: A classic associative array implementation with keys and values. Hashtable is synchronized.
•HashMap: An implementation just like Hashtable except that it accepts null keys and values. Also, it is not