Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 6 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 6 David Davenport Computer Eng. Dept.,"— Presentation transcript:

1 Java Coding 6 David Davenport Computer Eng. Dept.,
Collections David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last update: 12/12/2016 ~added more detailed slides for ArrayLists Previously: 6/12/2012 ( split original into two parts, (1) ArrayLists & fixed size arrays, (2) variable sized arrays. )

2 IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 MusicCD Class Example MusicCD( title, artist, tracks)
String getTitle() String getArtist() Track getTrack(int) int getDuration() Date getReleaseDate() String title String Artist Date releaseDate ??? tracks Date( String) String toString() int year int month int day Write and test the Track and Date classes. To do the MusicCD class we need to store a collection of Tracks… use Java’s ArrayList (or Vector) class… Note: Later extend example to have a personal CD collection, which requires add/remove/search/sort/etc. note that the example code includes an interactive track builder that demos add/remove. Track( title, length) String getTitle() int getLength() String title int length collection of

4 Easy collections… Arraylists

5 [ milk, eggs, bread, honey ]
Easy Collections Use Java’s ArrayList class An object of the ArrayList class provides a container which can hold any number of other objects… NEAT! ArrayList() boolean add(Object) void add(int, Object) int size() Object get(int) Object remove(int) Object set(int, Object) Object clone() String toString() boolean equals( Object) ArrayList Methods above are part of Java’s Collections framework however, latest API is in terms of Generics, & more difficult to understand (start with this, explain problems + can add anything, so care needed when getting things back ~typecast + getting unexpected type crashes program ~ so future-proof with generics + later talk about adding primitive types rather than Objects + MyInt, Integer, autoboxing-unboxing. Vector equivalent to ArrayList (which is unsynchronised whereas Vector is synchronised!) List is abstract notion, elements in sequence duplicates allowed. Other implementations of List exist, e.g. LinkedList. Array is related to implementation, which we will come to shortly. For now think high-level abstraction (like shopping list or todo list!) Note: Later can try using the sort & search routines available with the Collection framework on this object. Objects arranged in a sequence: LIST [ milk, eggs, bread, honey ]

6 Example use… (1) import java.util.ArrayList; ArrayList list;
list = new ArrayList(); System.out.println( list ); list.add( “David” ); list.add( “Gunes” ); list.add( 0, “Derya” ); list.add( 1, new Date() ); list.add( new Person( “Ayse”, 18) ); ArrayList is in the java.util package As usual, create variable to hold it (reference to instance) Then create new instance, and put into variable. Then call methods… printing calls toString() of each object in list. can add any number of any Java (Object) type, neat eh? Note the compiler “warning” messages!

7 Example use… (2) System.out.println( list.size() );
list.remove( size()-1 ); list.set( 0, new Date( 1, 1, 2001) ); System.out.println( list ); System.out.println( list.get(0) ); Can add, remove, get number of elements, change element, etc. Can get any object as String (calls toString) But, can’t just get element and put into Date, for example (won’t compile since list may contain anything, so may not be Date). Must typecast to desired type… - BUT… you (the programmer) are taking responsibility! Date d = list.get(0); Date d = (Date) list.get(0); Object o = list.get(0); if ( o instanceof Date ) { Date d = (Date) o; System.out.println( d.getAge() ); }

8 ArrayList- with generics
Use Java’s ArrayList class ArrayList<E>() boolean add(E) void add(int, E) int size() E get(int) E remove(int) E set(int, E) Object clone() String toString() boolean equals( Object) ArrayList see Java API… <E> is element type …allows only that type to be added

9 Example use… (3) Solution: use generics… ArrayList<Date> list;
list = new ArrayList <Date>(); System.out.println( list ); list.add( new Date() ); list.add( “oops, no go!” ); Date d = list.get(0); System.out.println( d.getAge() ); Use Java’s Generics framework Specify type of elements Compiler won’t allow anything else to be added No need to typecast result; must be of specified type No more compiler “warning” messages!

10 ArrayList - & primitive types
Only object-types… solution? enclose primitive in object! DIY… “MyInt” class Java’s Integer (wrapper) class now with auto-boxing/unboxing!

11 DIY…wrapper ArrayList<MyInt> list;
public class MyInt { int value; public MyInt( int i) { value = i; } public int getValue() { return value; public String toString() { return value + “”; DIY…wrapper ArrayList<MyInt> list; list = new ArrayList<MyInt>(); list.add( new MyInt(5) ); list.add( new MyInt(7) ); list.add( new MyInt(3) ); System.out.println( list ); int i = list.get(0).getValue();

12 Java…wrapper ArrayList<Integer> list;
package java.lang; public class Integer { int value; public Integer( int i) { value = i; } public int intValue() { return value; public String toString() { return value + “”; Java…wrapper ArrayList<Integer> list; list = new ArrayList<Integer>(); list.add( new Integer(5) ); list.add( new Integer(7) ); list.add( new Integer(3) ); System.out.println( list ); int i = list.get(0).intValue(); Wrapper classes int – Integer char – Character double – Double boolean - Boolean

13 With auto box/unboxing…
ArrayList<Integer> list; list = new ArrayList<>(); list.add(5); list.add(7); list.add(3); System.out.println( list ); int i = list.get(0); for ( Integer j : list) System.out.println( j * 2 ); new diamond notation auto-boxing auto-unboxing new loop syntax

14 Easy Problem Read in a set of positive integer values and then print out a table showing the average, each of the values and their difference from the average. Example output… Umm… must remember all the values we read in in order to print the table. Average is 5 Value Diff Algorithm 1. read set of values (how? Fixed number, e.g. 4, ask user how many?, use sentinel?) 2. compute average of set of values (?divide by zero error?) 3. print table using average & set of values Cannot directly store primitive types in ArrayList + solution create own wrapper class, MyInt + use Java’s wrapper classes Integer, Double, etc. + utilise autoboxing/unboxing. Java’s wrapper classes have other useful methods, e.g. valueOf to convert string to int or double. ? Leave as exercise for students to do. ? Possible lab assignment? ? Now in book? Could use ArrayList… BUT integers are not Objects! (use Integer wrapper class)

15 Not so easy collections…
Arrays

16 Not-so-easy Collections
Arrays Common data structure All elements of same type Are Objects in Java Basis of ArrayList class! Each element has unique successor & predecessor (except first & last.) Data structure – grouping of data elements ? Data structure where elements are of different types? In Java they are Objects so everything you know about objects (&references) applies! Reason they are so common is easy to implement at low-level, even in hardware. Elements are stored sequentially from a starting address. Since the elements are the same, the size the occupy is the same. Hence, computing the address of any element from its index is easy! Difference btw ArrayList & Array? + ArrayList can have any number of any type of element + Array can only have one type of element, and number is fixed at creation and cannot be changed. Problem is how to implement ArrayList’s using lower-level Arrays… 3 6 5 1 10 2 4 grades Name for entire structure Each element identified by an index (label/subscript)

17 Array Syntax (1) Arrays are Objects, so
Array size cannot be changed after creation! Arrays are Objects, so declare variable then instantiate Note use of square brackets! type[] variableName ; variableName = new type[ noOfElements ]; Other examples double[] heights; String[] names; boolean[] flags; Doctor[] docs; … names = new String[100] Note: indexes (label/subscripts) always begin at zero and increase. Last one is noOfElements-1 If also have int[] results; what does results = grades; do? Alternative is results = grades.clone(); -- but shallow clone by default! IMPORTANT: number of elements in array cannot be changed after array is created! Note: Initializer lists… (maybe leave until later?) int[] grades = { 10, 3, 6, 5, 1}; For some reason can only use this when declaring array, not afterwards! Useful for constants such as String[] daysOfWeek = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”}; 3 6 5 1 10 2 4 grades int[] grades; grades = new int[5];

18 Array Syntax (2) Referring to an individual element
variableName[index] Where index is a literal, named constant, variable, or expression. examples grades[0] grades[ i] grades[1] grades[ i+1] names[99] names[ FIRST] Can do anything with individual element that you can do with normal variable of the same type. Note: index must be between 0 & noOfElements in array – 1, else ArrayIndexOutOfBoundsException! grades[0] = 10; grades[1] = grades[0] + 2; System.out.println( grades[0]); names[99] = scan.nextLine();

19 Processing all elements
e.g. Printing contents of array grades System.out.println( grades[0] ); System.out.println( grades[1] ); : for ( int i = 0; i < ___________; i++) System.out.println( grades[i] ); Cannot print array directly System.out.println( grades): // doesn’t work! So, must do it element by element… ? How many elements does the array have? - write number, e.g. 5 - define named constant final int NOOFELEMENTS = 5; (or variable) & use when creating array & processing it - use the length property… length is property (not method!) of arrays – returns number of elements the array has. Use this example as pattern for processing all elements of an array. e.g. summing them to find average, finding minimum, whether in ascending order or not, … for ( int i = 0; i < grades.length; i++) System.out.println( grades[i] ); for each int k in grades array print k // alternate for syntax for ( int k : grades) System.out.println( k);

20 Easy Problem using arrays!
Printing table of differences from average 1. read set of values 2. compute average of set of values 3. print table of differences using average & set of values Steps 2 & 3 are straightforward For step 1 need to know how many values Fixed, e.g. 5 Ask user Use sentinel - but length of array is fixed! Using sentinel is problem since size of array cannot be changed after it has been created. Catch-22 ! We will come back to that problem later… For now, demo straightforward implementation.

21 Easy Problem with Methods!
Identify method signatures from algorithm int[] readSetOfValues() 1. read set of values double computeAverage( int[] setOfValues) 2. compute average of set of values Have already written the algorithm & identified information flowing from one statement to another. This gave us our data requirements. Now want to implement each step as a method call. Identify information flowing into and out of a step. The output of a step is the method result. The inputs to a step are the method parameters. Note: If parameters are object-type, then they can act as input and outputs too. e.g. Step 1 might be done like this… void readSetOfValues( int[] setOfValues) but requires the array to be instantiated with the correct number of elements before calling (this method then simply changes the values of the elements). void printTable( double average, int[] setOfValues) 3. print table of differences using average & set of values Data Requirements: average – double setOfValues – int[] Note: Object-type parameters can act as outputs too!

22 Arrays of objects Array contains only references to objects
Track[] tracks; tracks = new Track[5]; Still need to create actual objects tracks[0] = new Track( “David”, 100); tracks[1] = new Track( “Gunes”, 200); Array element is object, so call its methods as normal – variableName.methodName(parameters) Caution: do not attempt to access non-existent object! Since elements can be any sort of object, they may be other arrays – giving multi-dimensional arrays! 1 2 3 4 tracks David 100 Gunes 200 tracks[0].getTitle() tracks[4].getTitle()


Download ppt "Java Coding 6 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google