• No results found

5COSC019W - OBJECT ORIENTED PROGRAMMING Lecture 5: Introduction to Collections (ArrayLists) and Arrays

N/A
N/A
Protected

Academic year: 2021

Share "5COSC019W - OBJECT ORIENTED PROGRAMMING Lecture 5: Introduction to Collections (ArrayLists) and Arrays"

Copied!
23
0
0

Loading.... (view fulltext now)

Full text

(1)

Dimitris C. Dracopoulos 1/23

5COSC019W - OBJECT ORIENTED PROGRAMMING

Lecture 5: Introduction to Collections (ArrayLists) and Arrays

Dr Dimitris C. Dracopoulos

(2)

Dimitris C. Dracopoulos 2/23

Collections

The Collections is a set of classes found in the java.util package.

Compared with arrays, collection classes:

I Can hold a number of objects as elements (arrays can store both primitives and objects).

I They can have an unlimited number of objects.

I Although primitives cannot be stored directly, wrapper classes

can be used to store the value of a primitive in a wrapper

object. Such an object can be stored in a collection class.

(3)

Dimitris C. Dracopoulos 3/23

The ArrayList class

An example of a class belonging to Java Collections. An unlimited number of objects can be stored in an ArrayList.

Example:

import java.util.*;

public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> al = new ArrayList<String>();

// Add three elements in the list al.add("aa");

al.add("bb");

al.add("ccc");

for (int i=0; i < al.size(); i++) { String s = al.get(i);

System.out.println(s);

}

(4)

Dimitris C. Dracopoulos 4/23

// remove second element from the list al.remove(1);

System.out.println("After remove(), al contains:");

for (String e : al)

System.out.println(e);

}

}

(5)

Dimitris C. Dracopoulos 5/23

When the above program is run, it displays:

aa bb ccc

After remove(), al contains:

aa

ccc

(6)

Dimitris C. Dracopoulos 6/23

Wrappers and Storing Numbers in Collections

Primitives cannot be stored directly in a collection class. The Java library contains wrapper classes which correspond to primitives as they are capable to store a primitive value.

Double d1 = new Double(3.1);

Double d2 = 3.1; //automatically creates a Double object from 3.1

(7)

Dimitris C. Dracopoulos 7/23

Example:

import java.util.*;

public class WrapperExample {

public static void main(String[] args) {

// create an ArrayList object storing Double objects ArrayList<Double> a = new ArrayList<Double>();

Double d1 = new Double(5.4);

a.add(d1);

a.add(11.2); // autoboxing occurs

// (double -> Double conversion) //a.add(new Integer(2)); // Error!

// get second element from arraylist Double d2 = a.get(1);

// get 1st element - unboxing occurs

// (Double -> double conversion) double d3 = a.get(0);

System.out.println("d2=" + d2 + ", d3=" + d3);

} }

(8)

Dimitris C. Dracopoulos 8/23

When the above example is run, it displays:

d2=11.2, d3=5.4

(9)

Dimitris C. Dracopoulos 9/23

Non-parameterised ArrayLists

Although non-recommended, an ArrayList object can be declared to store objects of any type. In such cases, explicit casting is required when obtaining an element from the list.

import java.util.*;

public class ArrayListExample2 {

public static void main(String[] args) { ArrayList l1 = new ArrayList();

l1.add(new Integer(11));

l1.add(new Integer(3));

l1.add(new Integer(55));

for (int i=0; i < l1.size(); i++) {

Integer k1 = (Integer) l1.get(i); // Cast is required!

System.out.println(k1);

} } }

(10)

Dimitris C. Dracopoulos 10/23

Arrays

A constant number of primitive types or objects can be stored in an array.

I Java arrays are objects (they are allocated in the heap).

Declaring an array int a[];

Creating an array object a = new int[5];

The size of an array cannot be changed once it is created.

Memory

a

a[0]

a[4]

a[3]

a[2]

a[1]

int a[] = new int[5];

(11)

Dimitris C. Dracopoulos 11/23

Example:

/**

A class to simulate the operation of a lottery

*/

public class Lottery { int results[];

/**

Constructs a lottery object with empty results

*/

public Lottery() {

results = new int[6];

}

(12)

Dimitris C. Dracopoulos 12/23

/**

Simulates the lottery draw by filling in array results.

The random generator should be called normally, but this class demonstrates arrays so for simplicity numbers are fixed.

*/

public void draw() { results[0] = 11;

results[1] = 45;

results[2] = 3;

results[3] = 24;

results[4] = 12;

results[5] = 31;

}

/**

Prints on the screen the latest draw results

*/

public void printResults() {

System.out.println("The latest lottery results are:");

for (int i=0; i < results.length; i++) System.out.print(results[i] + " ");

System.out.println();

}

(13)

Dimitris C. Dracopoulos 13/23

public static void main(String[] args) { Lottery lot = new Lottery();

lot.draw();

lot.printResults();

} }

When the above program is run, it displays:

The latest lottery results are:

11 45 3 24 12 31

(14)

Dimitris C. Dracopoulos 14/23

Initialising Arrays

There are two ways to initialise an array:

I Assign a value to each element individually.

double b[] = new double[10];

b[0] = 5.0;

b[1] = 1.2;

I Use an array initialiser at the point of declaration:

String weekdays[] = {"Mon", "Tue", "Wed", "Thu", "Fri"};

or

String weekdays[] = new String[] {new String("Mon"),

new String("Tue"),

new String("Wed"),

new String("Thu"),

new String("Fri")};

(15)

Dimitris C. Dracopoulos 15/23

Two Dimensional Arrays (Arrays of Arrays)

A 2-dimensional array in Java is an array of an array.

Book mybooks [] [];

mybooks = new Book[10][12]; // an array[10] of array[12]

Because object declarations as the one above, do not create objects, an array of an array must create the elements in it, before using the array:

mybooks[i][j] = new Book();

This is also illustrated in the example below:

class Book { String colour;

}

public class ArrayExample {

public static void main(String[] args) {

Book mybooks [] [] = new Book[10][12]; // an array[10]

// of array[12]

System.out.println(mybooks[0][0]);

mybooks[0][0] = new Book();

System.out.println(mybooks[0][0]);

} }

(16)

Dimitris C. Dracopoulos 16/23

When the program is run it prints:

null

Book@f6a746

null null null null

null null

0 1 2

0 1

(a) After:

Book m [] [] = new Book[2][3];

null null null null

0 1 2

0 1

Book

object Book object

m[1][1] = new Book();

m[0][0] = new Book();

(b) After:

(17)

Dimitris C. Dracopoulos 17/23

Looping over Arrays - The for-each loop

public class ArrayExample2 {

public static void main(String[] args) { String a[] = new String[3];

a[0] = "aa";

a[1] = "bb";

a[2] = "cc";

System.out.println("Array a contains:");

for (String i : a) System.out.println(i);

/* an array of an array containing different number of elements in each row */

int myNumbers[][] = new int[][] { {0}, {0,1}, {0,1,2}, {0,1,2,3}};

System.out.println("\nArray myNumbers contains:");

(18)

Dimitris C. Dracopoulos 18/23

for (int[] r : myNumbers) { // for each row

for (int c : r) { // for each element in current row System.out.print(c + " ");

}

System.out.println();

} } }

(19)

Dimitris C. Dracopoulos 19/23

The above code displays:

Array a contains:

aa bb cc

Array myNumbers contains:

0

0 1

0 1 2

0 1 2 3

(20)

Dimitris C. Dracopoulos 20/23

Another array example:

public class ArrayReferencesExample {

public static void main(String[] args) { int a[] = new int[3];

a[0] = -1;

a[1] = 5;

a[2] = 4;

int b[];

b = a;

System.out.println("a is located at address " + a +

", b is located at address " + b);

a = new int[5];

for (int i=0; i < 5; i++) a[i] = i+1;

System.out.println("After a = new int[5]");

System.out.println("a is located at address " + a +

", b is located at address " + b);

(21)

Dimitris C. Dracopoulos 21/23

System.out.println("\n a contains: ");

for (int n : a)

System.out.print(n + " ");

System.out.println("\n b contains: ");

for (int n : b)

System.out.print(n + " ");

System.out.println(); // add a newline }

}

(22)

Dimitris C. Dracopoulos 22/23

0x126b249 0x126b249

a

b

int a[] = new int[3];

a[0] = −1;

a[1] = 5;

a[2] = 4;

−1 5 4

0xf6a746

−1 5 4

1 2 3 4 5

a) After: b) After: a = new int[5];

for (int i=0; i < 5; i++) a[i] = i+1;

a

b

b = a;

int b[];

(23)

Dimitris C. Dracopoulos 23/23

The Arrays class

The Arrays library class located in package java.util, provides a number of useful utilities to manipulate arrays.

These include:

I Fill parts (or the whole) of the array with values.

I Compare arrays element by element I Search.

I Sort.

References

Related documents

The fundamental problems of the linguistic situation in Ukraine are the lack of consensus regarding the issue of what role the Ukrainian language has in constructing

Although the MLAH strategy is the most effective one when raising fluently speaking bilinguals, the OPOL strategy can also work: the results in Sjöberg’s study

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the

Bankin6 Sector plays an important role in economic development of a country( 9he  bankin6 system of India is featured by a lar6e net'ork of bank branches8 servin6 many kinds

Content Outline: This session examines the different ways to evaluate technologies for young children, focusing on the different factors, in particular the role of adults, which

Object-Oriented Design: The List Abstract Data Type (ADT) p.. From the Java Library: The Java Collections Framework and Generic

• The field variables of an object can be used by any method of that object just like a variable defined in the method.. Access Outside

An added benefit of the AVG CloudCare go-to-market model is that it allows solution providers to bundle the security service with other support and managed services pricing..