Java Coding 6 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

Java Coding OOP David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Towards Event-driven programming &
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Java Coding 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Decisions, decisions…!
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Arrays Chapter 7.
Lecture 5:Interfaces and Abstract Classes
CMSC 202 ArrayList Aug 9, 2007.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
User-Written Functions
Java Coding – part 2 David Davenport Computer Eng. Dept.,
(like an array on steroids)
Array, Strings and Vectors
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Chapter 7 Part 1 Edited by JJ Shepherd
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept.,
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Java How to Program, Late Objects Version, 10/e
Lecture 2: Implementing ArrayIntList reading:
ArrayLists.
CS Week 9 Jim Williams, PhD.
CMSC 202 ArrayList Aug 9, 2007.
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
BIT115: Introduction to Programming
Java Coding 6-extra David Davenport Computer Eng. Dept.,
CMSC 202 ArrayList Aug 9, 2007.
Grouped Data Arrays, and Array Lists.
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
slides created by Ethan Apter
ArrayLists 22-Feb-19.
7 Arrays.
CS 200 Objects and ArrayList
Suggested self-checks: Section 7.11 #1-11
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
slides created by Alyssa Harding
CSE 143 Lecture 2 ArrayIntList, binary search
Review: libraries and packages
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Consider Write a program that prompts a user to enter the number of students and then, their names and grades. The program will then outputs the average.
CS 200 Objects and ArrayList
Java Coding 6 David Davenport Computer Eng. Dept.,
Arrays.
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 6 David Davenport Computer Eng. Dept., Collections David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr 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. )

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 email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

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

Easy collections… Arraylists

[ 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 ]

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!

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() ); }

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

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!

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

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();

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

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

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 -------------- 10 5 3 -2 6 1 1 -4 -------------- 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)

Not so easy collections… Arrays

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)

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];

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();

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);

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.

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!

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()