300 likes | 381 Views
Arrays, List<E> and Iterator<E>. COMP 401, Spring 2014 Lecture 7 1 / 30 /2014. Array Review. Ordered sequence of elements Elements must be of the same type Fixed size once created Valid indices from 0 to length-1 Arrays are reference types
E N D
Arrays, List<E> and Iterator<E> COMP 401, Spring 2014 Lecture 7 1/30/2014
Array Review • Ordered sequence of elements • Elements must be of the same type • Fixed size once created • Valid indices from 0 to length-1 • Arrays are reference types • Have fields and methods like other object types • In particular, size of array is available through length field • Declaring variables that can hold an array reference • type[] variable_name
Creating Empty Arrays • With new keyword as in: • int[] iarray = new int[10]; • Point[] parray = new Point[7]; • What do we mean by empty? • For array of value of types • Elements get default value • 0 for numeric • false for boolean • For array of reference types • Elements set to null • You need to set each element after you create the array to point to either existing or new object. • Can create and initialize array with literal syntax as in: • int[] iarray = new int[] {1, 2, 6, 8, 10}; • Point[] parray = new Point[] {new Point(0,0), new Point(1,2), new Point(3,4)};
Arrays as Reference Types • Same reference, same array • Implication for arrays passed to methods • When an array is passed to a method, any changes that the method makes to its elements is permanent. • Potential danger with object state • If holding object state in an array, easy to accidentally break encapsulation and expose object state to alteration. • Array cloning • Easy way to create a “shallow” copy of an array • Just call clone() method • Result will be a new array of same size with same values or references
Multidimensional Arrays • Multidimension array is simply an array of arrays • Fill out dimensions left to right. int[][] marray = new int[5][]; for(inti=0; i<5; i++) { marray[i] = new int[10]; } • Each Sub-dimension can have independent size. • Sometimes known as as a “ragged” or “uneven” array int[][] marray = new int[5][]; for (inti=0; i<5; i++) { marray[i] = new int[i+1]; } • If each sub-dimension is same size, can create with a single new statement • int[][] marray = new int[5][10];
Arrays utility class • Arrays is a library of useful functions for manipulating arrays • Note “s” in Arrays • Like Math class, all methods are static • binarySearch • sort • filling and copying subranges • http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
Java Collection Framework • Arrays are not resizeable • Often need a collection of items that acts like an array that can grow or shrink • Java Collection Framework • In package java.util • Defines a set of interfaces for resizeable collections • List • Ordered by integer index • Set • Unordered, no duplicate elements • Map • Indexed by an arbitrary key • Sometimes known as a “dictionary” • Provides a set of classes that implement these interfaces in specific ways • Examples for List: ArrayList, LinkedList,
Java Collections as Generics • Java Collection Framework interfaces and classes are “generic” • Interface/class name is modified to specify type in the collection. • ArrayList<E> implements List<E> • E is a placeholder • Must be filled in by an actual type name when used. • For now, just want to have working knowledge of List as an interface and ArrayList as a collection that implements the interface.
List<E> • boolean add(E val) • Adds val to end of list and returns true • void add(int index, E val) • Inserts val as position index • E get(int index) • Returns element at position index • E set(int index, E val) • Sets element at position index, returns original value for element • E remove(int index) • Removes element at position index, list shrinks • int size() • Returns current size of list • booleanisEmpty() • Same as testing size() == 0 • E[] toArray(E[] a) • Converts list to an array given current elements
ArrayList<E> • ArrayList<E> is an implementation of List<E> • Uses an array internally • lec07.ex1
Design Situation • Suppose we have an object that encapsulates some sort of collection. • SongLibrary • A collection of songs in an iTunes-like system • PolygonModel • A collection of polygons in a 3D modeling system
Design Situation • Now suppose we have code outside of this collection object that needs to examine each element of the underlying collection in turn. • SongFilter • A object that represents a search criteria to be applied to a collection of songs • An intersection test in which each polygon of a PolygonModel needs to be evaluated
Strategy 1: Provide access to underlying collection as an array. • SongLibrary • public Song[] getSongs() • PolygonModel • public Polygon[] getPolygons() • Drawbacks? • May have to do a lot of work to create the array • Collection may be result of generative process • There may be no “end” to the collection. • Or the collection may be large so we don’t want to provide the whole thing at once.
Strategy 2: Provide index access to each underlying item in collection • SongLibrary • public intgetNumSongs(); • public Song getSong(intsong_idx); • PolygonModel • public intgetNumPolygons(); • public Polygon getPolygon(intpolygon_idx); • Drawbacks? • Doesn’t help with generative collections • Imposes restrictions on how collection is represented and linearized • Deteriorates encapsulation
Strategy 3: Internalize a “cursor” • SongLibrary • public void resetSongCursor(); • public Song getNextSong(); • public booleanisCursorAtEnd(); • Drawbacks? • Can’t have two traversals going at the same time. • But, this does come close.
Iterator Design Pattern • “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation” • Gang of Four, Design Patterns • Consider: for(inti=0; i<slist.size(); i++) { Song next_song = slist.get(i); // Do something with next_song. }
Iterator Design Pattern • Iterator object encapsulates details of item traversal. • Understands details of the underlying collection. • Manages order of items • May want a traversal that is not just first to last. • Underlying collection may not have a natural linear order. • Manages state of traversal • Allows traversal to be picked up again later. • Assumption: underlying collection is not changed or modified while the traversal is occurring. • Iterator should be able to detect this and signal an error • Variant of pattern will have iterator provide methods that modify underlying collection safely
Componentsof Iterator Pattern • Collection object is “iterable” • Provides a method that returns an object that acts as an iterator. • Iterator object provides access to the elements in turn. • At the very least: • A method to test whether more items exist. • A method to retrieve the next item. • Other possible features: • Methods that remove an item safely. • Method to “peek” at the next item. • Method to reset the traversal.
Java Iterator Pattern Interfaces • The Java Collections Framework defines two generic interfaces for supporting the iterabledesign pattern • Implemented by the various collection types such as List<E>, Map<E>, Set<E>, etc. • Iterable<E> • Interator<E> iterator() • Iterator<E>
Iterator<E> • booleanhasNext() • Are we at the end of the traversal? • E next() • Get the next item of the traversal. • Throws a runtime exception if no next item. • void remove() • Not supported by all implementations. • Safely removes last item retrieved by next() from the underlying collection.
Iterable examples • lec07.ex2 • Main1 • Simple use • Main2 • Parallel iterators • Main3 • Simultaneous iterators • Main4 • for – each syntactic sugar
Main1 Visualized (1) ArrayList<Song> slist Words and Guitar 0 Dig Me Out 1 Jenny 2 Little Babies 3 Buy Her Candy 4
Main1 Visualized (2) Iterator<Song> iter ArrayList<Song> slist list Words and Guitar 0 next_idx 0 Dig Me Out 1 Jenny 2 Little Babies 3 Buy Her Candy 4
Main1 Visualized (3) Iterator<Song> iter ArrayList<Song> slist list Words and Guitar 0 next_idx 0 Dig Me Out 1 Jenny 2 public booleanhasNext() { if (next_idx < list.size()) { return true; } return false; } Little Babies 3 Buy Her Candy 4 NOTE: This may or may not be how it is actually implemented, but it is effectively what is going on.
Main1 Visualized (4) Iterator<Song> iter ArrayList<Song> slist list Words and Guitar 0 next_idx 1 Dig Me Out 1 Jenny 2 public Song next() { Song s = list.get(next_idx); next_idx++; return s; } Little Babies 3 Buy Her Candy 4 NOTE: Real implementation would first check to see if hasNext() is still true and throw an exception otherwise.
lec07.ex2.Main2 • Parallel iteration • Processes two different lists • Iterator associated with each. • Iterators advance unevenly
lec07.ex2.Main3 • Simultaneous iteration • 2 Iterators, 1 List • Insert your own joke here.
for - each • Java provides “syntactic sugar” for a particularly common use of iterators. • for-each loop • Supposing e_coll is Iterable<E>, then these are equivalent: Iterator<E> iter = e_coll.iterator(); while (iter.hasNext()) { E elem = iter.next(); // Do something with element } for (E elem : e_coll) { // Do something with elem } • lec07.ex2.Main4
for-each with Array • The for-each construct also works with Arrays • Useful if you need to process the elements of an array but do not need the index. String[] names = new String[] {“Amy”, “Mike”, “Cameron”, “Claire”}; for (String n : names) { System.out.println(n); }
lec07.ex3 • A more complicated iterator • Can build iterators that do things other than just go through every item. • Prior examples made use of Iterator<E> built into List<E>, here we are going to implement our own specialized version of Iterator<E>