150 likes | 224 Views
Arrays, List<E> and Iterator<E>. COMP 401, Spring 2013 Lecture 6 1/29/2013. Array Basics. 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
E N D
Arrays, List<E> and Iterator<E> COMP 401, Spring 2013 Lecture 6 1/29/2013
Array Basics • 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)}; • lec6.v1
Processing Arrays • Often need to loop over all values of an array • Common pattern for doing this: for (inti=0; i<a.length; i++) { // Deal with a[i] } • for – each construct can be used if index variable is not actually needed for anything other than retrieving the element for (Point p : parray) { // Loop variable p set to each element // of parray in turn. } • lec6.v2
Arrays as Reference Types • Same reference, same array • Saw this a little bit in lec6.v1 • 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 • Equivalent to array copy code example in lec6.v2 • lec6.v3
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]; • lec6.v4
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
Assignment 2 • Be sure to clone array of Point objects passed to PolygonImpl constructor. • Similarly, be sure to clone array to return as a result of getPoints() • Notes about area and centroid formulas • Tester will be released tomorrow.
Java Collection Framework • Arrays are not resizeable • Often need a collection of items that acts like an array than 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 Collection Framework interfaces and classes are “generic” • Interface/class is modified to specify type of object in collection • For now, just want to have working knowledge of List and ArrayList
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 • lec6.v5
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. } COMP 401 :: Spring 2012
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 be linear. • 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. COMP 401 :: Spring 2012
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<E> • Has an iterator() method that provides an Iterator<E> COMP 401 :: Spring 2012
Iterable example • lec6.v6 • Main1 • Simple use • Main2 • Parallel iterators COMP 401 :: Spring 2012