Collection of Data Objectives Using arrays Generics Allowing

Collection of Data

Objectives Using arrays Generics: Allowing operations not tired to a specific data type Classes: Vector and Array. List [CS 1020 Lecture 4: Collection of Data] 2

Outline (1/2) 1. Array 1. 1 1. 2 1. 3 1. 4 1. 5 1. 6 1. 7 1. 8 1. 9 Introduction Array in C Array in Java Array as a Parameter Detour: String[] in main() method Returning an Array Common Mistakes 2 D Array Drawback [CS 1020 Lecture 4: Collection of Data] 2. Generics 2. 1 2. 2 2. 3 2. 4 2. 5 2. 6 2. 7 Motivation Example: The Int. Pair Class (non-generic) The Generic Pair Class Autoboxing/unboxing The Generic New. Pair Class Using the Generic New. Pair Class Summary 3

Outline (2/2) 3. Vector 3. 1 3. 2 3. 3 Motivation API Documentation Example 4. Array. List 4. 1 4. 2 4. 3 Introduction API Documentation Example [CS 1020 Lecture 4: Collection of Data] 4

1 Array A collection of homogeneous data

1. Array Introduction n n Array is the simplest way to store a collection of data of the same type (homogeneous) It stores its elements in contiguous memory q q Array index begins from zero Example of a 5 -element integer array A with elements filled A 24 7 -3 15 9 A[0] A[1] A[2] A[3] A[4] [CS 1020 Lecture 4: Collection of Data] 6

1. Array in C (1/2) #include <stdio. h> #define MAX 6 int scan. Array(double [], int); void print. Array(double [], int); double sum. Array(double [], int); // To read values into arr and return // the number of elements read. int scan. Array(double arr[], int max_size) { int size, i; printf("How many elements? "); scanf("%d", &size); if (size > max_size) { printf("Exceeded max; you may only enter"); printf(" %d values. n", max_size); size = max_size; } printf("Enter %d values: ", size); for (i=0; i<size; i++) { scanf("%lf", &arr[i]); } return size; int main(void) { double list[MAX]; int size; size = scan. Array(list, MAX); print. Array(list, size); printf("Sum = %fn", sum. Array(list, size)); return 0; } } [CS 1020 Lecture 4: Collection of Data] sum_array. c 7

1. Array in C (2/2) sum_array. c // To print values of arr void print. Array(double arr[], int size) { int i; for (i=0; i<size; i++) printf("%f ", arr[i]); printf("n"); } // To compute sum of all elements in arr double sum. Array(double arr[], int size) { int i; double sum = 0. 0; for (i=0; i<size; i++) sum += arr[i]; return sum; } [CS 1020 Lecture 4: Collection of Data] 8

1. Array in Java (1/2) n In Java, array is an object. n Every array has a public length attribute (it is not a method!) Test. Array 1. java public class Test. Array 1 { public static void main(String[] args) { int[] arr; // arr is a reference Declaring an array: datatype[] array_name // create a new integer array with 3 elements // arr now refers (points) to this new array arr = new int[3]; Constructing an array: array_name = new datatype[size] // using the length attribute System. out. println("Length = " + arr. length); Length = ? arr[0] = 100; Accessing individual arr[0] = ? arr[1] = arr[0] - 37; array elements. arr[1] = ? arr[2] = arr[1] / 2; arr[2] = ? for (int i=0; i<arr. length; i++) System. out. println("arr[" + i + "] = " + arr[i]); } } [CS 1020 Lecture 4: Collection of Data] 9

1. Array in Java (2/2) n n Alternative loop syntax for accessing array elements Illustrate to. String() method in Arrays class to print an array Test. Array 2. java public class Test. Array 2 { public static void main(String[] args) { // Construct and initialise array double[] arr = { 35. 1, 21, 57. 7, 18. 3 }; // using the length attribute System. out. println("Length = " + arr. length); Length = 4 for (int i=0; i<arr. length; i++) { 35. 1 21. 0 57. 7 18. 3 System. out. print(arr[i] + " "); 35. 1 21. 0 57. 7 18. 3 } [35. 1, 21. 0, 57. 7, 18. 3] System. out. println(); // Alternative way Syntax (enhanced for-loop): for (datatype e: array_name) for (double element: arr) { System. out. print(element + " "); Go through all elements in the array. “e” automatically refers to the array element } sequentially in each iteration System. out. println(); System. out. println(Arrays. to. String(arr)); } } [CS 1020 Lecture 4: Collection of Data] Using to. String() method in Arrays class 10

1. Array as a Parameter n The reference to the array is passed into a method q Any modification of the elements in the method will affect the actual array public class Test. Array 3 { public static void main(String[] args) { int[] list = { 22, 55, 33 }; Test. Array 3. java swap(list, 0, 2); for (int element: list) System. out. print(element + " "); System. out. println(); } // To swap arr[i] with arr[j] public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } [CS 1020 Lecture 4: Collection of Data] 11
![1. Array Detour: String[] in main() method n The main() method contains a parameter 1. Array Detour: String[] in main() method n The main() method contains a parameter](http://slidetodoc.com/presentation_image_h/28d4a25bd1f64445bc5e52c07af0bb7b/image-12.jpg)
1. Array Detour: String[] in main() method n The main() method contains a parameter which is an array of String objects n We can use this for command-line arguments Test. Command. Line. Args. java public class Test. Command. Line. Args { public static void main(String[] args) { for (int i=0; i<args. length; i++) System. out. println("args[" + i + "] = " + args[i]); } } java Test. Command. Line. Args The "Harry Potter" series has 7 books. args[0] = The args[1] = Harry Potter args[2] = series args[3] = has args[4] = 7 args[5] = books. [CS 1020 Lecture 4: Collection of Data] 12

1. Array Returning an Array can be returned from a method public class Test. Array 4 { public static void main(String[] args) { double[] values; values = make. Array(5, 999. 0); for (double value: values) { System. out. println(value + " "); } Return type: datatype[] } Test. Array 4. java 999. 0 499. 5 333. 0 249. 75 199. 8 // To create an array and return it to caller public static double[] make. Array(int size, double limit) { double[] arr = new double[size]; for (int i=0; i < arr. length; i++) arr[i] = limit/(i+1); return arr; } } [CS 1020 Lecture 4: Collection of Data] 13

1. Array Common Mistakes (1/3) n length versus length() q To obtain length of a String object str, we use the length() method n q To obtain length (size) of an array arr, we use the length attribute n n Example: str. length() Example: arr. length Array index out of range q Beware of Array. Index. Out. Of. Bounds. Exception public static void main(String[] args) { int[] numbers = new int[10]; . . . for (int i = 1; i <= numbers. length; i++) System. out. println(numbers[i]); } [CS 1020 Lecture 4: Collection of Data] 14

1. Array Common Mistakes (2/3) n When you have an array of objects, it’s very common to forget to instantiate the array’s objects. n Programmers often instantiate the array itself and then think they’re done – that leads to java. lang. Null. Pointer. Exception n Example on next slide q It uses the Point class in the API q Refer to the API documentation for details [CS 1020 Lecture 4: Collection of Data] 15
![1. Array Common Mistakes (3/3) Point[] array = new Point[3]; array for (int i=0; 1. Array Common Mistakes (3/3) Point[] array = new Point[3]; array for (int i=0;](http://slidetodoc.com/presentation_image_h/28d4a25bd1f64445bc5e52c07af0bb7b/image-16.jpg)
1. Array Common Mistakes (3/3) Point[] array = new Point[3]; array for (int i=0; i<array. length; i++) { array[i]. set. Location(1, 2); null } null There are no objects referred to by array[0], array[1], and array[2], so how to call set. Location() on them? ! Corrected code: array null x 01 y 02 Point[] array = new Point[3]; for (int i=0; i<array. length; i++) { array[i] = new Point(); x 01 y 02 array[i]. set. Location(1, 2); } [CS 1020 Lecture 4: Collection of Data] x 01 y 02 16

1. Array 2 D Array (1/2) n n A two-dimensional (2 D) array is an array of array. This allows for rows of different lengths. // an array of 12 arrays of int[][] products = new int[12][]; int[][] array 2 D = { {4, 5, 2}, {1, 3}, {7, 1, 5, 6} }; 4 array 2 D 5 2 1 3 7 1 5 6 [CS 1020 Lecture 4: Collection of Data] 17

1. Array 2 D Array (2/2) array 2 D 4 5 2 public class Test 2 DArray { public static void main(String[] args) { int[][] array 2 D = { {4, 5, 2}, {1, 3}, {7, 1, 5, 6} }; 7 1 5 6 1 3 System. out. println("array 2 D. length = " + array 2 D. length); for (int i = 0; i < array 2 D. length; i++) System. out. println("array 2 D[" + i + "]. length = " + array 2 D[i]. length); } } for (int row = 0; row < array 2 D. length; row++) { for (int col = 0; col < array 2 D[row]. length; col++) System. out. print(array 2 D[row][col] + " "); System. out. println(); } array 2 D. length = 3 Test 2 DArray. java [CS 1020 Lecture 4: Collection of Data] array 2 D[0]. length = ? array 2 D[1]. length = ? array 2 D[2]. length = ? ? 18

1. Array Drawback n Array has one major drawback: q q q n Check API documentation and explore it yourself However, we will not be using this Array class much; we will be using some other classes such as Vector or Array. List q n Reconstruction is required if the array size changes To overcome such limitation, we can use some classes related to array Java has an Array class q n Once initialized, the array size is fixed Differences between Vector and Array. List are in slide 40 Before doing Vector/Array. List, we will introduce another concept called Generics [CS 1020 Lecture 4: Collection of Data] 19

2 Generics Allowing operation on objects of various types

2. Generics Motivation n There are programming solutions that are applicable to a wide range of different data types q n In C, there is no easy way to exploit the similarity: q n The code is exactly the same other than the data type declarations You need a separate implementation for each data type In Java, you can make use of generic programming: q A mechanism to specify solution without tying it down to a specific data type [CS 1020 Lecture 4: Collection of Data] 21

2. Generics Eg: The Int. Pair Class (non-generic) n Let’s define a class to: q q Store a pair of integers, e. g. (74, -123) Many usages, can represent 2 D coordinates, range (min to max), height and weight, etc. class Int. Pair { Int. Pair. java private int first, second; public Int. Pair(int a, int b) { first = a; second = b; } public int get. First() { return first; } public int get. Second() { return second; } } [CS 1020 Lecture 4: Collection of Data] 22

2. Generics Using the Int. Pair Class (non// This program uses the Int. Pair class to create an object generic) // containing the lower and upper limits of a range. // We then use it to check that the input data fall within // that range. Enter a number in (-5 to 20): -10 import java. util. Scanner; Enter a number in (-5 to 20): 21 public class Test. Int. Pair { Enter a number in (-5 to 20): 12 public static void main(String[] args) { Int. Pair range = new Int. Pair(-5, 20); Scanner sc = new Scanner(System. in); int input; do { System. out. printf("Enter a number in (%d to %d): ", range. get. First(), range. get. Second()); input = sc. next. Int(); } while( input < range. get. First() || input > range. get. Second() ); } } [CS 1020 Lecture 4: Collection of Data] Test. Int. Pair. java 23

2. Generics Observation n The Int. Pair class idea can be easily extended to other data types: q n double, String, etc. The resultant code would be almost the same! class String. Pair { private String first, second; Only differences are the data type declarations public String. Pair( String a, String b ) { first = a; second = b; } public String get. First() { return first; } public String get. Second() { return second; } } [CS 1020 Lecture 4: Collection of Data] 24

2. Generics The Generic Pair Class class Pair <T> { private T first, second; public Pair(T a, T b) { first = a; second = b; } public T get. First() { return first; } public T get. Second() { return second; } } n Pair. java Important restriction: q q q The generic type can be substituted by reference data type only Hence, primitive data types are NOT allowed Need to use wrapper class for primitive data type [CS 1020 Lecture 4: Collection of Data] 25

2. Generics Using the Generic Pair Class public class Test. Generic. Pair { Test. Generic. Pair. java public static void main(String[] args) { Pair<Integer> two. Int = new Pair<Integer>(-5, 20); Pair<String> two. Str = new Pair<String>("Turing", "Alan"); // You can have pair of any reference data types! // Print out the integer pair System. out. println("Integer pair: (" + two. Int. get. First() + ", " + two. Int. get. Second() + ")"; // Print out the String pair System. out. println("String pair: (" + two. Str. get. First() + ", " + two. Str. get. Second() + ")"; } } n The formal generic type <T> is substituted with the actual data type supplied by the user: q The effect is similar to generating a new version of the Pair class, where T is substituted [CS 1020 Lecture 4: Collection of Data] 26

2. Generics Autoboxing/unboxing (1/2) n The following statement invokes autoboxing Pair<Integer> two. Int = new Pair<Integer>(-5, 20); n Integer objects are expected for the constructor, but -5 and 20, of primitive type int, are accepted. n Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes q n The primitive values -5 and 20 are converted to objects of Integer The Java compiler applies autoboxing when a primitive value is: q q Passed as a parameter to a method that expects an object of the corresponding wrapper class Assigned to a variable of the correspond wrapper class [CS 1020 Lecture 4: Collection of Data] 27

2. Generics Autoboxing/unboxing (2/2) n n Converting an object of a wrapper type (e. g. : Integer) to its corresponding primitive (e. g: int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is: q q Passed as a parameter to a method that expects a value of the corresponding primitive type Assigned to a variable of the corresponding primitive type int i = new Integer(5); // unboxing Integer int. Obj = 7; // autoboxing System. out. println("i = " + i); System. out. println("int. Obj = " + int. Obj); int a = 10; Integer b = 10; // autoboxing System. out. println(a == b); [CS 1020 Lecture 4: Collection of Data] i = 5 int. Obj = 7 true 28

2. Generics The Generic New. Pair Class n n We can have more than one generic type in a generic class Let’s modify the generic pair class such that: q Each pair can have two values of different data types class New. Pair <S, T> { private S first; private T second; You can have multiple generic data types. Convention: Use single uppercase letters for generic data types. public New. Pair(S a, T b) { first = a; second = b; } public S get. First() { return first; } public T get. Second() { return second; } } [CS 1020 Lecture 4: Collection of Data] New. Pair. java 29

2. Generics Using the Generic New. Pair Class public class Test. New. Generic. Pair { Test. New. Generic. Pair. java public static void main(String[] args) { New. Pair<String, Integer> someone = new New. Pair<String, Integer>("James Gosling", 55); System. out. println("Name: " + someone. get. First()); System. out. println("Age: " + someone. get. Second()); } } n Name: James Gosling Age: 55 This New. Pair class is now very flexible! q Can be used in many ways [CS 1020 Lecture 4: Collection of Data] 30

2. Generics Summary n Caution: q q n Generics are useful when the code remains unchanged other than differences in data types When you declare a generic class/method, make sure that the code is valid for all possible data types Additional Java Generics topics (not covered): q Generic methods q Bounded generic data types q Wildcard generic data types [CS 1020 Lecture 4: Collection of Data] 31

3 Vector class Class for dynamic-size arrays

3. Vector Motivation n Java offers a Vector class to provide: q Dynamic size n q Generic n q n expands or shrinks automatically allows any reference data types Useful predefined methods Use array if the size is fixed; use Vector if the size may change. [CS 1020 Lecture 4: Collection of Data] 33
![3. Vector API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 34 3. Vector API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 34](http://slidetodoc.com/presentation_image_h/28d4a25bd1f64445bc5e52c07af0bb7b/image-34.jpg)
3. Vector API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 34

PACKAGE API documentation (2/3) SYNTAX 3. Vector import java. util. Vector; //Declaration of a Vector reference Vector<E> my. Vector; //Initialize a empty Vector object my. Vector = new Vector<E>; Commonly Used Method Summary boolean is. Empty() Tests if this vector has no components. int size() Returns the number of components in this vector. [CS 1020 Lecture 4: Collection of Data] 35

3. Vector API documentation (3/3) Commonly Used Method Summary (continued) boolean add(E o) Appends the specified element to the end of this Vector. void add(int index, E element) Inserts the specified element at the specified position in this Vector. E remove(int index) Removes the element at the specified position in this Vector. boolean remove(Object o) Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged. E get(int index) Returns the element at the specified position in this Vector. int index. Of(Object elem) Searches for the first occurrence of the given argument, testing for equality using the equals method. boolean contains(Object elem) Tests if the specified object is a component in this vector. [CS 1020 Lecture 4: Collection of Data] 36

3. Vector Example Test. Vector. java import java. util. Vector; public class Test. Vector { Output: public static void main(String[] args) {[CS 1010, CS 1020, CS 2010] At index 0: CS 1010 Vector<String> courses; CS 1020 is in courses CS 1010 courses = new Vector<String>(); CS 2010 courses. add("CS 1020"); courses. add(0, "CS 1010"); courses. add("CS 2010"); Vector class has a nice to. String() method that prints all elements System. out. println(courses); System. out. println("At index 0: " + courses. get(0)); if (courses. contains("CS 1020")) System. out. println("CS 1020 is in courses"); courses. remove("CS 1020"); for (String c: courses) System. out. println(c); } } [CS 1020 Lecture 4: Collection of Data] The enhanced for-loop is applicable to Vector objects too! 37

4 Array. List class Another class for dynamic-size arrays

4. Array. List Introduction (1/2) n Java offers an Array. List class to provide similar features as Vector: q Dynamic size n q Generic n q n allows any reference data types Useful predefined methods Similarities: q q n expands or shrinks automatically Both are index-based and use an array internally Both maintain insertion order of element So, what are the differences between Vector and Array. List? q This is one of the most frequently asked questions, and at interviews! [CS 1020 Lecture 4: Collection of Data] 39

4. Array. List n Introduction (2/2) n Vector Array. List Since JDK 1. 0 Since JDK 1. 2 Synchronised * (thread-safe) Not synchronised Slower (price of synchronisation) Faster ( 20 – 30%) Expansion: default to double the size of its array (can be set) Expansion: increases its size by 50% Array. List is preferred if you do not need synchronisation n n Differences between Vector and Array. List Java supports multiple threads, and these threads may read from/write to the same variables, objects and resources. Synchronisation is a mechanism to ensure that Java thread can execute an object’s synchronised methods one at a time. When using Vector /Array. List, always try to initialise to the largest capacity that your program will need, since expanding the array is costly. n Array expansion: allocate a larger array and copy contents of old array to the new one [CS 1020 Lecture 4: Collection of Data] 40
![4. Array. List API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 41 4. Array. List API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 41](http://slidetodoc.com/presentation_image_h/28d4a25bd1f64445bc5e52c07af0bb7b/image-41.jpg)
4. Array. List API documentation (1/3) [CS 1020 Lecture 4: Collection of Data] 41

PACKAGE API documentation (2/3) SYNTAX 4. Array. List import java. util. Array. List; //Declaration of a Array. List reference Array. List<E> my. Array. List; //Initialize a empty Array. List object my. Array. List = new Array. List<E>; Commonly Used Method Summary boolean is. Empty() Returns true if this list contains no element. int size() Returns the number of elements in this list. [CS 1020 Lecture 4: Collection of Data] 42

4. Array. List API documentation (3/3) Commonly Used Method Summary (continued) boolean add(E e) Appends the specified element to the end of this list. void add(int index, E element) Inserts the specified element at the specified position in this list. E remove(int index) Removes the element at the specified position in this list. boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. E get(int index) Returns the element at the specified position in this list. int index. Of(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. boolean contains(Object elem) Returns true if this list contains the specified element. [CS 1020 Lecture 4: Collection of Data] 43

4. Array. List Example import java. util. Array. List; import java. util. Scanner; Test. Array. List. java public class Test. Array. List { public static void main(String[] args) { Scanner sc = new Scanner(System. in); Array. List<Integer> list = new Array. List<Integer>(); System. out. println("Enter a list of integers, press ctrl-d to end. "); while (sc. has. Next()) { list. add(sc. next. Int()); } Output: Enter a list. . . to end. 31 System. out. println(list); // using Array. List's to. String() 17 -5 // Move first value to last 26 list. add(list. remove(0)); 50 (user pressed ctrl-d here) System. out. println(list); [31, 17, -5, 26, 50] } [17, -5, 26, 50, 31] } [CS 1020 Lecture 4: Collection of Data] 44

Summary Java Elements Array: - Declaration and common usage Generics: - Allowing operation on objects of various types Vector and Array. List: - Dynamic-size arrays - Declaration and useful methods [CS 1020 Lecture 4: Collection of Data] 45
- Slides: 45