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 &
Everyday Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction to.
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.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
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!
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
ArrayList, Multidimensional Arrays
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
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 +
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
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…
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Java Coding 6 David Davenport Computer Eng. Dept.,
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Java Coding – part 2 David Davenport Computer Eng. Dept.,
(like an array on steroids)
Array, Strings and Vectors
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
COP 3503 FALL 2012 Shayan Javed Lecture 8
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
CS 106A, Lecture 19 ArrayLists
TCSS 143, Autumn 2004 Lecture Notes
Lecture 2: Implementing ArrayIntList reading:
Java Coding 4 David Davenport Computer Eng. Dept.,
ArrayLists.
CS Week 9 Jim Williams, PhD.
CS 200 Objects and ArrayList
CMSC 202 ArrayList Aug 9, 2007.
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.
CS 200 Objects and ArrayList
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
ArrayLists 27-Apr-19.
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.,
Generics 2-May-19.
CS 200 Objects and ArrayList
Java Coding 6 David Davenport Computer Eng. Dept.,
Arrays.
Why not just use Arrays? Java ArrayLists.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 6 David Davenport Computer Eng. Dept., Collections – using ArrayLists David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Last update: 11/12/2017 ~ArrayLists (separated from arrays) & tidied slides up a bit. Previously: 12/12/2016 ~added more detailed slides for ArrayLists 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.

Arraylists Easy collections… Maintaining collections of things is a common task Not surprisingly, Java provides a neat solution (actually lots of them, but we will focus on one this semester) The ArrayList class… What operations are necessary for collections? - add/insert, remove, change, get one, process all, instantiate, … 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 ] First is at index 0 Last is at index size()-1

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( list.size()-1 ); list.set( 0, new Date( 1, 1, 2001) ); System.out.println( list ); System.out.println( list.get(0) ); // can use for loop to process entire list for (int i = 0; i < list.size(); i++) { Date d = (Date) list.get(i); if ( d.isToday() ) System.out.println( “Happy ” + d.getAge() + “th Birthday” ); } 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! Programs compile, but may crash when run if unexpected type of object found! Can use “instanceof” operator very sparingly but generally not recommended! Note this problem is potentially serious & why compiler gives warning messages! Date d = list.get(0); // no go! Date d = (Date) list.get(0); Object o = list.get(0); if ( o instanceof Date ) { // caution 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 actual Java API… <E> is element type …allows only that type to be added Generics framework was introduced in Java 1.5 Allows programmer to restrict type of elements the list can hold. Compiler can now enforce adding only this type of element to list & so guarantees get(i) will return the specified type (no need for typecast; no risk of crashing; no warning messages!)

Example use… (3) Solution: using 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 – of anything? What can ArrayLists not contain? Can hold only object-types, so… must enclose primitive in object! DIY… “MyInt” class Java’s Integer (wrapper) class now with auto-boxing/unboxing! value {int} {MyInt} x Surprisingly ArrayLists can hold ArrayLists (since they are objects) and can even hold themselves! But can’t directly hold primitive types: int, double, char, boolean, etc.

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(); value {int} {MyInt} x

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 ints are not Objects! (use Integer wrapper class)