Title: Review Generics and the ArrayList Class
1Review Generics and the ArrayList Class
2Generics
- Added to Java v5.0
- Generics class and method definitions may
include parameters for types - Generic program type parameter allows one to
write code that applies to any class - Ex. list of items of type T
- When TDouble, its a list of Doubles, etc.
3ArrayList
- Advantage
- Can grow or shrink (arrays cant)
- import java.util.ArrayList
- See http//java.sun.com/j2se/1.5.0/docs/api/java/u
til/ArrayList.html
4ArrayList
- Disadvantage
- Less efficient than arrays
- Lacks familiar syntax (Java limitation,
supported by C) - Base type must be an object (not primitive) type
- Can have ArrayList of Integer but cant have an
ArrayList of int. - Less of a problem w/ automatic boxing and
unboxing - Java limitation, supported by C
5ArrayList class
- Define an ArrayList of Strings
- ArrayListltStringgt list new ArrayListltStringgt()
- Define an ArrayList of Employees
- ArrayListltEmployeegt empList
- new ArrayListltEmployeegt( 20 )
- Initial capacity is specified as 20.
6ArrayList class
- Set an element
- list.set( 12, Hi, Mom. )
- Get an element
- System.out.println( list.get( 12 ) )
- String s list.get( 5 )
7ArrayList class
- Add an element add( value ) form
- list.add( One )
- list.add( Two )
- list.add( Three )
- One is at position 0, Two is at position 1,
and Three is at position 2.
8ArrayList class
- Add an element add( i, value ) form
- i must be a used position or the first unused
position - list.add( One )
- list.add( Two )
- list.add( Three )
- list.add( 1, Fred )
- One is at position 0, Fred is at position 1,
Two is at position 2, and Three is at
position 3.
9ArrayList class
- size() method
- for (int i0 iltlist.size() i)
- System.out.println( list.get(i) )
10ArrayList class methods
11ArrayList class methods
- public ArrayListltBase_Typegt( int initialCapacity
) - public ArrayListltBase_Typegt()
- initial capacity is 10
12ArrayList class methods
- Array-like methods
- public Base_Type set ( int index, Base_Type
newElement ) - where 0ltindexltsize() (or exception)
- public Base_Type get ( int index )
- where 0ltindexltsize() (or exception)
13ArrayList class methods
- Methods to add elements
- public boolean add ( Base_Type newElement )
- adds the new element to the end
- size() increases by 1
- capacity increases if necessary
14ArrayList class methods
- Methods to add elements
- public void add ( int index, Base_Type newElement
) - 0ltindexltsize()
- when indexsize(), inserts at end
- size() increases by 1
- capacity increases if necessary
- when 0ltindexltsize(), current elements at index
move to index1, at index1 move to index2, ,
at size()-1 move to size()
15ArrayList class methods
- Methods to remove elements
- public Base_Type remove ( int index )
- 0ltindexltsize() (or exception)
- Removes element at index shifts to the left
remaining elements at index1 size()-1. - protected void removeRange ( int fromIndex, int
toIndex ) - Removes elements with index i s.t.
fromIndexltilttoIndex shifts to the left
remaining elements at toIndex size()-1
16ArrayList class methods
- Methods to remove elements
- public boolean remove( Object theElement )
- if found then removes the first occurrence of
theElement shifts the remaining elements to the
left size() becomes size()-1 returns true. - if not found then returns false.
- public void clear ( )
- Removes all elements size() becomes 0
17ArrayList class methods
- Search methods
- public boolean contains ( Object target )
- Uses equals() method of target
- True if ArrayList contains target false
otherwise. - public int indexOf ( Object target )
- Uses equals() method of target
- Returns index of first occurrence of target in
ArrayList -1 otherwise. - public int lastIndexOf ( Object target )
- Same as above except index of last occurrence is
returned.
18ArrayList class methods
- Memory management (size capacity)
- public boolean isEmpty ( )
- True if empty false otherwise.
- public int size ( )
- Returns number of elements in ArrayList
- public void ensureCapacity ( int newCapacity )
- Increases the capacity (if necessary)
- public void trimToSize ( )
- Reduces capacity to current size
19ArrayList class methods
- Make a copy
- public Object toArray ( )
- Returns an array of list elements (in order).
- PublicltTypegt Type toArray ( Type a )
- Returns an array of list elements (in order).
- If list will fit in array a, it will be used
remaining elements of a will be null. - If list wont fit in array a, a new array will be
created and used. - public Object clone ( )
- Returns a shallow copy of the ArrayList.
20ArrayList class methods
- Equality
- public boolean equals ( Object other )
- True only when both are of the same size, and
both have the same elements (in the same order).
21for-each loop
- for (Array_Base_Type var Collection_Object)
- Statement
- Let myList be an ArrayList of Strings.
- for (String element myList)
- System.out.println( element )
22for-each loop
- The for-each loop also works with arrays
- // Returns the sum of the elements of a
- int sum ( int a )
- int result 0
- for (int item a)
- result item
- return result
23Generics
24Generics
- Classes and methods can have a type parameter
(actually, more than one). - The type parameter can be any reference (class)
type. - (started with Java version 5.0 in C as well
but much restricted in Java) - Generic class parameterized class class with
a parameter for a type
25Generic methods
- public class Utility
-
- public staticltTgt T getMidpoint ( T a )
- return a a.length/2
-
- public staticltTgt T getFirst ( T a )
- return a0
-
-
26Generic methods
- public class Utility
- public staticltTgt T getMidpoint ( T a )
- return a a.length/2
-
- public staticltTgt T getFirst ( T a )
- return a0
-
-
- //usage
- String midString Utility.ltStringgtgetMidPoint(
b ) - double firstNumber Utility.ltDoublegtgetFirst( c
)
27Generic (parameterized) classes
- public class SampleltTgt
- private T data
- public void setData ( T newData )
- data newData
-
- public T getData ( )
- return data
-
28Generic (parameterized) classes
- public class SampleltTgt
- private T data
- public void setData ( T newData )
- data newData
-
- public T getData ( )
- return data
-
-
- //usage
- SampleltStringgt object new SampleltStringgt()
- object.setData( Hello )
29Generic class for ordered pairs
- PairltStringgt secretPair
- new PairltStringgt( Happy, Day )
- PairltIntegergt rollOfDice
- new PairltIntegergt( new Integer(2),
- new Integer(3) )
- Pet male new Pet()
- Pet female new Pet()
- PairltPetgt breedingPair
- new PairltPetgt( male, female )
30Defining the ordered pair class
- public class PairltTgt
- private T first
- private T second
- public Pair ( )
- first null
- second null
-
- public Pair ( T f, T s )
- first f
- second s
-
-
31Defining the ordered pair class
- public class PairltTgt
- private T first
- private T second
-
- //These are suggested by our author.
- //Why are they bad?
- public T getFirst ( ) return first
- public T getSecond ( ) return second
-
32Defining the ordered pair class
- public class PairltTgt
- private T first
- private T second
-
- //These are suggested by our author.
- //Why are they bad?
- //potential privacy leaks!
- public T getFirst ( ) return first
- public T getSecond ( ) return second
-
33Defining the ordered pair class
- public class PairltTgt
- private T first
- private T second
-
- public boolean equals ( Object other )
- if (othernull) return false
- if (getClass() ! other.getClass()) return
false - PairltTgt o (PairltTgt)other
- return first.equals(o.first)
second.equals(o.second) -
-
34More then one type parameter can be specified
- PairltString,Integergt
- p new PairltString,Integergt( Kyle Jones,
- new Integer(123456789) )
35Defining the ordered pair class
- public class PairltT1,T2gt
- private T1 first
- private T2 second
- public Pair ( )
- first null
- second null
-
- public Pair ( T1 f, T2 s )
- first f
- second s
-
-
36Defining the ordered pair class
- public class PairltT1,T2gt
- private T1 first
- private T2 second
-
- public T1 getFirst ( ) return first
- public T2 getSecond ( ) return second
-
37Defining the ordered pair class
- public class PairltT1,T2gt
- private T1 first
- private T2 second
-
- public boolean equals ( Object other )
- if (othernull) return false
- if (getClass() ! other.getClass()) return
false - PairltT1,T2gt o (PairltT1,T2gt)other
- return first.equals(o.first)
second.equals(o.second) -
-
38Bounds for type parameters
- Say I wish to restrict my type parameter T to
only those things that implement the Comparable
interface. - Can I do this?
- What happens if I use the compareTo() method
without stating this restriction?
39Bounds for type parameters
- Say I wish to restrict my type parameter T to
only those things that implement the Comparable
interface. - Can I do this?
- Yes.
- What happens if I use the compareTo() method
without stating this restriction? - A compiler error occurs.
40Bounds for type parameters
- Example of stating this restriction
- public class PairltT extends Comparablegt
-
The keyword extends is used rather than
implements because T must be a class (not an
interface).
41Multiple bounds
- Multiple bounds may also be specified.
- For example,
- public class AnotherGenericlt
- T1 extends Employee Comparable,
- T2 extends Comparablegt
-
-
- But only 1 may be a class. The rest must be
interfaces. Why?
42Problem 1
- In the sport of diving, seven judges award a
score between 0.0,10.0. The highest and lowest
scores are discarded. The remaining scores are
added together. The sum is then multiplied by
the degree of difficulty 1.2,3.8 for that dive.
The result is then multiplied by 0.6 to
determine the divers score. - Write a program that inputs the degree of
difficulty and the 7 judges score, and outputs
the divers score. - You are required to use an ArrayList of Double
for the judges scores.
43Problem 2
- Write a program that uses an ArrayList of
parameter type Contact to store a database of
contracts. - The Contract class should store the contacts
first and last name, phone number, and email
address. Add appropriate accessor and mutator
methods. - Your program should present a textual menu that
allows the user to add a contact, display all
contacts, search for a specific contact and
displays it, or search for a specific contact and
give the user the option to delete it. The
searches should find any contact where any member
variable contains a target search string. For
example, if elmore is the search target then
any contact where the first name, last name,
phone number, or email address contains elmore
should be returned for display or deletion. - Use the for-each loop to iterate through the
ArrayList.
44Problem 3
- Many GPS can record waypoints. The waypoint
marks the coordinates of a location on a map
along with a timestamp. Our GPS stores waypoints
in terms of an (X,Y) coordinate on a map together
with a timestamp t that records the number of
seconds that have elapsed since the unit was
turned on. - Write a program that allows the user to enter as
many waypoints as desired, storing each in an
ArrayList of a class that you design. - As waypoints are entered, calculate the average
speed of the trip so far. (The distance between
(0,0) to (1,0) is 0.1 miles.)
45Problem 4
- Write a generic class, MyMathClass, with a type
parameter T where T is a numeric object type
(e.g., Integer, Double, or any class that extends
java.lang.Number). - Add a method named standardDeviation that takes
an ArrayList of type T and returns as a double
the standard deviation of the values in the
ArrayList. - Use the doubleValue() method in the Number class
to retrieve the value of each number as a double. - Your program should generate a compile-time error
if your standard deviation method is invoked on
an ArrayList that is defined for non-numeric
elements (e.g., String). - Additionally, use the for-each in the
standardDeviation method.
46Problem 5
- Create a generic class with a type parameter that
simulates drawing an item at random out of a box.
This class could be used for simulating a random
drawing. - For example the box might contain Strings
representing names written on a slip of paper, or
the box might contain Integers representing a
random drawing for a lottery based on numeric
lottery picks. - Create an add method that allows the user of the
class to add an object of the specified type
along with an isEmpty method that determines
whether or not the box is empty. - Finally, your class should have a drawItem method
that randomly selects an object from the box and
returns it. If the user attempts to draw an item
out of an empty box, return null. - Write a main method that tests your class. To
generate a random number x, where 0ltxlt1, use x
Math.random().