0% found this document useful (0 votes)
12 views26 pages

Oop - 5

The document provides an overview of Object-Oriented Programming with a focus on arrays and collections in Java. It explains the structure, creation, and operations of arrays, including examples of searching, inserting, and deleting elements. Additionally, it covers various collection types such as List, Set, and Map, detailing their characteristics and implementations.

Uploaded by

josephwelch042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views26 pages

Oop - 5

The document provides an overview of Object-Oriented Programming with a focus on arrays and collections in Java. It explains the structure, creation, and operations of arrays, including examples of searching, inserting, and deleting elements. Additionally, it covers various collection types such as List, Set, and Map, detailing their characteristics and implementations.

Uploaded by

josephwelch042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

OBJECT ORIENTED

PROGRAMMING
YSS#

Ref 1: Deitel & Deitel (2010). Java How to Program (8th


ed.). Prentice Hall

Ref 2: Lindholm, T. & Yellin, F. (2007). The Java Virtual


Machine Specification (2nd ed.). Addison-Wesley

Ref 3: Gosling, J., Bill, J., Steele, G. & Bracha, G. (2005).


The Java Language Specification (3rd

ed.). Addison-Wesley.
ARRAYS & COLLECTIONS
Arrays
-> Array is the most commonly used data storage structure; it’s built into most programming languages

-> Used to keep track of a numbered group of related objects or types

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]

To display value at position 5:


System.out.Println(“Marks at position 5: ”+ marksArray[5])
Arrays ~~

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:

/** Adds all the numbers in an integer array. */


public static int sum(int[] marksArray) {
int total = 0;
for (int i=0; i < marksArray.length; i==) // note the use of the length variable
total += marksArray[i];
return total;
}

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

One way to declare and initialize an array is as follows:


element_type[] array_name = {init_val_0,init_val_1,…,init_val_N−1};
The element_type can be any Java base type or class name, and array_name can be any value Java identifier.
The initial values must be of the same type as the array. For example, consider the following declaration of
an array that is initialized to contain the first ten prime numbers:
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; //declare, initialize & initialize
Another Way:
int[] intArray; // defines a reference to an array
intArray = new int[100]; // creates the array,initializes and sets intArray to refer to it

Or you can use the equivalent single-statement approach:


int[] intArray = new int[100];

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 [] a =new int[10];

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.

The output of the program looks like this:


77 99 44 55 22 88 11 0 66 33
Found 66
77 99 44 22 88 11 0 66 33
Array Operations

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

✓ A collection is a single object designed to manage a group of objects.


✓ Objects in a collection are called elements.
✓ Primitives are not allowed in a collection.
✓ Various collection types implement many common data structures:
✓ Stack, queue, dynamic array, hash
✓ The Collections API relies heavily
on generics for its implementation.
Collection Implementation

Type Implementation

List ArrayList LinkedList

Set TreeSet HashSet LinkedHashSet

Map HashMap HashTable TreeMap

Deque ArrayDeque
List

o List defines generic list behavior.


o Is an ordered collection of elements
o List behaviors include:
o Adding elements at a specific index
o Getting an element based on an index
o Removing an element based on an index
o Overwriting an element based on an index
o Getting the size of the list
o List allows duplicate elements.
ArrayList

• Is an implementation of the List type


– The list automatically grows if elements exceed initial size.
• Has a numeric index
– Elements are accessed by index.
– Elements can be inserted based on index.
– Elements can be overwritten.
• Allows duplicate items
List<Integer> partList = new ArrayList<>(3);
partList.add(new Integer(1111));
partList.add(new Integer(2222));
partList.add(new Integer(3333));
partList.add(new Integer(4444)); // ArrayList auto grows
System.out.println("First Part: " + partList.get(0)); // First item
partList.add(0, new Integer(5555)); // Insert an item by index
Generic ArrayList
Stores items of specific type – e.g objects of student class, objects of customer class ~

public class GenericArrayList {


public static void main(String args[]) {
List<Integer> partList = new ArrayList<>(3);

partList.add(new Integer(1111));
partList.add(new Integer(2222));
partList.add(new Integer(3333));
partList.add("Bad Data"); // compiler error now

Iterator<Integer> elements = partList.iterator();


while (elements.hasNext()) {
Integer partNumberObject = elements.next();
int partNumber = partNumberObject.intValue();

System.out.println("Part number: " + partNumber);


}
}
}
Set

• A Set is an interface that contains only unique elements.

• A Set has no index.

• Duplicate elements are not allowed.

• You can iterate through elements to access them.

• TreeSet provides sorted implementation.

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

public class SetExample {


public static void main(String[] args){
Set<String> set = new TreeSet<>();

set.add("one");
set.add("two");
set.add("three");
set.add("three"); // not added, only unique

for (String item:set){


System.out.println("Item: " + item);
}
}
}
Map
• A collection that stores multiple key-value pairs
– Key: Unique identifier for each element in a collection
– Value: A value stored in the element associated with the key
• Called “associative arrays” in other languages
Example
Key Value
101 Blue Shirt
102 Black Shirt
103 Gray Shirt
Map Types

•TreeMap: A map where the keys are automatically sorted

•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

synchronized (multiple threads can access simultaneously).


TreeMap: Implementation of Map

public class MapExample {


public static void main(String[] args){
Map <String, String> partList = new TreeMap<>();
partList.put(“S001", "Blue Polo Shirt");
partList.put(“S002", "Black Polo Shirt");
partList.put(“H001", "Duke Hat");

partList.put(“S002", "Black T-Shirt"); // Overwrite value


Set<String> keys = partList.keySet();

System.out.println("=== Part List ===");


for (String key:keys){
System.out.println("Part#: " + key + " " +
partList.get(key));
} Output
} === Part List ===
Part#: H002 Duke Hat
} Part#: S001 Blue Polo Shirt
Part#: S002 Black T-Shirt
Deque Type

A collection that can be used as a stack or a queue

➢ It means a “double-ended queue” (and is pronounced “deck”).

➢ A queue provides FIFO (first in, first out) operations:

➢ add(e) and remove() methods

➢ A stack provides LIFO (last in, first out) operations:

➢ push(e) and pop() methods


Stack with Deque: Example

public class TestStack {


public static void main(String[] args){
Deque<String> stack = new ArrayDeque<>();
stack.push("one");
stack.push("two");
stack.push("three");

int size = stack.size() - 1;


while (size >= 0 ) {
System.out.println(stack.pop());
size--;
}
}
}

You might also like