Download presentation
Presentation is loading. Please wait.
Published byΑσπασία Διαμαντόπουλος Modified over 5 years ago
1
Java Coding 6 David Davenport Computer Eng. Dept.,
Collections – using ArrayLists David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. 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/ ~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
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
4
[ 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
5
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!
6
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() ); }
7
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!)
8
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!
9
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.
10
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
11
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
12
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
13
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 ints are not Objects! (use Integer wrapper class)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.