the java collections framework and lists in javamarkw/class/cs2334/lecture notes/04-jcfa… · •...

52
The Java Collections Framework and Lists in Java – Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale

Upload: others

Post on 02-Jun-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

The Java Collections Framework and Lists in Java – Parts 1 & 2

Chapter 9Chapter 6 (6.1-6.2.2)

CS 2334University of OklahomaBrian F. Veale

Page 2: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 2

• Data are very important to Software Engineering– Data is a plural word– The concept of groups of objects is natural – Storage or Manipulation of groups of objects is

a very common development task.• You will spend a lot of time working with

groups of data in software development– Many of the problems in Computer Science

deal with manipulating large groups of data

Groups of Data

Page 3: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 3

• If you’ve taken a programming class, you’ve used an array– Arrays allow us to put similar data in a

cohesive unit– Implementation dependent

:Student :Student :Student :Student :Student

0 1 2 3 4myClass

Arrays

Page 4: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 4

• The Java Collections Framework (JCF) includes many ways to manipulate groups of data– Library of classes, objects, and methods for

grouping data– Also designed as a “framework”

• Skeletal support for something being constructed

• The JCF is designed to be systematically extended and reused

The Java Collections Framework

Page 5: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 5

• The most general object in the JCF is the Collection interface– A group of generic Object elements– Most of the collection interfaces work on

Objects• Type casting is common when using Collections

– Java 1.5.0 removes a lot of the need for casting through the use of generics.

• instanceof operator• ClassCastException

JCF Collections

Page 6: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 6

• boolean contains(Object target) - Returns true if target is one of the Objects stored in the Collection.

• boolean containsAll(Collection c) - Returns true if every element in Collection c is also one of the Objects stored in the Collection, and false otherwise.

• boolean isEmpty()• Iterator iterator() - Used to list the Contents of the Collection

in order.• Object[] toArray()• Object[] toArray(Object[] typeArray) - Returns an array

containing the elements in this Collection whose type (not contents) comes from the type of elements in typeArray.

• int size()

Required Methods in Collection

Page 7: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 7

• boolean add(Object element)• boolean addAll(Collection objs) - Add all the Add all the

elements from Collection elements from Collection objsobjs to this to this Collection.Collection.

• boolean clear()•• booleanboolean remove(Objectremove(Object target)target)• boolean removeAll(Collection c) - Remove all

the elements in Collection c from this Collection.

• boolean retainAll(Collection c) -Remove all Remove all the elements in this Collection, except for the elements in this Collection, except for those that are in Collection c.those that are in Collection c.

Optional Methods in Collection

Page 8: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 8

• Demo: CollectionDemo.java

The Collection Interface in Action

Page 9: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 9

Person and Student Design

+ S tu d e n t(p N a m e: S tr in g , p ID L S tr in g , p H o u rs : in t, p G P A : flo a t) : v o id+ g e tH o u rs () : in t+ g e tG P A (): flo a t+ s e tH o u rs (p H o u rs : in t) : v o id+ s e tG P A (p G P A : flo a t) : v o id

-h o u rs : in t-g p a : flo a t

S tu d e n t

+ P e rs o n (p N a m e : S tr in g , p ID : S tr in g ): v o id+ g e tN a m e (): S tr in g+ g e tID () : S tr in g+ g e tE m a il() : S tr in g+ s e tE m a il(a d d re s s : S tr in g ): v o id+ g e tS ta tu s () :in t

-n a m e : S tr in g- id : S tr in g-e m a il: S tr in g

P e rs o n

< < in te r fa c e> >C o m p a ra b le

+ c o m p a re T o ( o b j: O b je c t ) : in t

< < in te r fa c e > >S e ria liz a b le

< < in te rfa c e > >C lo n e a b le

Page 10: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 10

• Classes that provide useful methods for manipulating objects that implement Collection

• Cannot be instantiated– Not because it is an interface– It has no public constructor, only static

methods– Similar to the Math class.

Collections

Page 11: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 11

• Object min( Collection c )– Returns the smallest element in Collection c

• Object max( Collection c )– Returns the largest element in Collection c

• The classes of the objects contained in the Collection c must implement comparable– Otherwise our friend ClassCastException

will be thrown

Useful methods from Collections

Page 12: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 12

• Demo: CollectionSort.java– Notice use of casting....– In Java 1.4.* and earlier you must cast the

String back into a String (as shown).– For this code to compile without warnings

you must use the following compilation commandJavac -source 1.4 CollectionSort.java

Collections in Action

Page 13: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 13

• Lists are a common way to store data– Grocery Lists– Class Rosters

• Lists are more than a collection– What does a list imply?– What do we do to lists that we don't do to

collections?

Lists

Page 14: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 14

• Lists are one of the most common ADTs• Linear

– Elements are stored in a fixed order– Collection by itself doesn't guarantee any type of

ordering– A collection can be unsorted or sorted in some order

• Alphabetically• By size• By date• Etc.

• List is a interface– ArrayList, LinkedList, etc. each implement List

The List ADT

Page 15: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 15

• A Collection is ordered if the elements are in a predictable sequence.

• A Collection is sorted if the elements are ordered according to some criterion like Strings being ordered alphabetically

Definitions: Ordered and Sorted

Page 16: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 16

• Collection methods become more specific when included in a List ADT.

• add( Object element ) in Collection– Says nothing about where the object is added,

only that it is added.• We will add an object to the end of a list

– Intuitive way to add to a list.– Helps increase the efficiency of adding.

• We don't have to traverse the list to figure out where to add the element.

Adding to a List

Page 17: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 17

add( “Kristina” )

AlexFreddieBrianBobCali

Sammy

AlexFreddieBrianBobCali

SammyKristina

Adding to a List: Example

Page 18: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 18

• Collection just guarantees that one copy of the object will be removed from the list

• Which copy to remove from a List should be clear.– First? Last? Middle?– Somewhat arbitrarily, we remove the first

occurrence.• These type of decisions should be very clear

in the documentation for the ADT.

Removing from a List

Page 19: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 19

AlexCali

FreddieBrianBobCali

Sammy

AlexFreddieBrianBobCali

Sammy

remove( “Cali” )

Removing from a List: Example

Page 20: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 20

• Many of the Collection class methods are modified by List

• Some methods needed to support a List cannot be implemented in Collection

• void add( int index, Object element )– What about the element currently in that position?

• Will it be replaced?• Will it be shifted by one position?

– To the left (up)?– To the right (down)?

Another way to add to a List

Page 21: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 21

AlexFreddieBrianBobCali

Sammy

AlexFreddieKatrina

BobCali

Sammy

AlexFreddieKatrina

BrianBobCali

Sammy

add( 2, “Katrina” )

replacing

shifting

Indexed Adding to a List: Example

Page 22: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 22

• List also supports adding an entire collection to the current collection– addAll( Collection c )

• Can we just call add( Collection c )?– This would add that the entire Collection as

one object.• This is not what you might expect.

Adding a Collection to a Collection

Page 23: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 23

AlexFreddieBrianBobCali

Sammy

AlexFreddieBrianBobCali

Sammy

add( Collection c )

Carl

Sue

James

Carl

Sue

James

c

Adding a Collection the wrong way

Page 24: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 24

AlexFreddieBrianBobCali

Sammy

AlexFreddieBrianBobCali

SammyJamesSueCarl

addAll( Collection c )

Carl

Sue

James

c

Adding a Collection the right way

Page 25: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 25

• We also want to be able to replace one element with another element

• This method follows the Java convention of set as a mutator– It changes the contents of the List

• set( 2, “Jenny” )

Replacing an element in the List

Page 26: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 26

AlexFreddieBrianBobCali

Sammy

AlexFreddieJennyBobCali

Sammy

set( 2, “Jenny” )

Replacing an element in a List: Example

Page 27: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 27

•• booleanboolean add(Objectadd(Object element) element) -- Add element to the end of Add element to the end of this List.this List.

•• booleanboolean addAll(CollectionaddAll(Collection objsobjs) ) -- Add all the elements from Add all the elements from Collection Collection objsobjs to end of this List.to end of this List.

•• void void add(intadd(int index, Object element) index, Object element) -- Add an element to Add an element to the given index location. Shift the other elements down.the given index location. Shift the other elements down.

•• void void addAll(intaddAll(int index, Collection index, Collection objsobjs) ) -- Insert all the Insert all the elements from Collection elements from Collection objsobjs to starting at the indexed to starting at the indexed value. Shift elements down to make room.value. Shift elements down to make room.

•• Object Object get(intget(int index) index) •• ListIteratorListIterator listIteratorlistIterator() () -- Returns a Returns a listIteratorlistIterator for this for this

CollectionCollection•• Object Object set(intset(int index, Object element)index, Object element)•• intint indexOf(ObjectindexOf(Object objobj))•• intint lastIndexOf(ObjectlastIndexOf(Object objobj))

List methods (only those changed List methods (only those changed or added to Collection):or added to Collection):

Page 28: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 28

• ListDemo.java– Notice what happens when we use addAll()

instead of add() on lines 88-89

List Demo

Page 29: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 29

• Programmers often want to traverse collections sequentially.

• Iterator – an object that allows us to move in order through a collection from one element to another

• Iterators make this process uniform.– It knows the details of the Collection– Not us

• Order in which the iterator moves through a collection is dependent on the type of collection being operated on

Accessing the Elements in a Collection

Page 30: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 30

• The Collection interface defines a method with the signature:

Iterator iterator()• It returns an iterator for it's “backing

collection”– This is the collection that the iterator is

connected to.

• All iterators implement at least three methods....

The iterator() method in Collection

Page 31: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 31

• boolean hasNext()– This method returns true if the iterator has more

items.– Obvious use: sentry value for while loops using

iterator• Object next()

– Returns the next item in the sequence and advances to the next position.

– Throws an exception if there is not a next position.• void remove()

– Removes the object from the list that was last returned by next().

– Not supported by all type of iterators.– Throws exception if last operation was not next().

Iterator methods

Page 32: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 32

• Lists can use a list iterator in addition to a regular Iterator– ListIterator contain extra functionality because

Lists are ordered

• Two methods exist in List to return a new ListIterator– ListIterator listIterator()

• Returns a ListIterator object for the entire List– ListIterator listIterator(int index)

• Returns a ListIterator that will return the element at position index first.

The ListIterator

Page 33: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 33

• boolean hasPrevious()– Returns true if the List has an element before the

current one.

• int nextIndex()– Returns the index of the next element in the List

• Object previous()– Returns the elements in the List before the current

element.

• int previousIndex()– Returns the index of the previous element in the

List

Methods that ListIterator adds to Iterator

Page 34: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 34

• remove()– ListIterator overrides the remove() method of Iterator– remove() removes the object from the list that was last

returned by next() or previous().• add()

– Inserts the new element into the list before/after the next element that would be returned by next()/previous(), respectively.

• set()– Replaces the last element returned by next() or

previous()

remove(), add(), and set() in ListIterator

Page 35: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 35

• ListIteratorDemo.java

ListIterator example:

Page 36: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 36

• Both can be used with a List– Only Iterator can be used for a Collection

• Which to use depends on your needs– Do you need the more specific ListIterator

methods?– If not necessary or useful, don’t use a

ListIterator.– In general, don’t use a more complex class

if a simpler one will suffice.

Iterator or ListIterator?

Page 37: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 37

• Collections class has many useful List-oriented methods

• Only make sense with List objects– These methods deal with ordered and/or

sorted Lists– Since Collection does not imply an order,

the methods aren’t useful

The Collections class and Lists

Page 38: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 38

• The Collections class can sort a List based on its natural ordering– The “natural ordering” is the one implemented in the

compareTo() method in your object.– Must implement Comparable to use.

• Incredibly useful method– Required for using some other Collections methods

like binarySearch()• Signature: Collections.sort(List list)

– Sorts the List list according to the order imposed by the compareTo() method of the objects stored in the list.

Collections.sort()

Page 39: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 39

• Binary searches are much more efficient than linear ones– Don’t need to go through all the

elements of a List to find our target– Faster on some types of lists than

others

Collections.binarySearch()

Page 40: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 40

Collections.binarySearch()

• Signature: int Collections.binarySearch(List list, Object key)

– Returns the index of the key if key is found in the list

– Returns (-(insertion point) - 1) if the key is not found in the List• Insertion point is the index of where the

key would be inserted if it was in the List• Return (-(insertion point) - 1) to ensure

that we only get a positive return value if the key is found in the List

Page 41: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 41

• ListSortAndSearch.java

Collections.sort() and Collections.binarySearch() Demo

Page 42: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 42

• We have been using ArrayList to implement a collection as a List

• ArrayList is not the only class that implements the List interface– ArrayList– LinkedList– Vector

Programming with Lists

Page 43: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 43

Implementation of ArrayList

• Size is 3• Capacity is 5

:Student :Student :Student

myClass

0 1 2 3 4

Page 44: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 44

• Random Access– Suppose each object reference takes up one

memory location– If the reference to element at index 32 is stored at

address 421, the reference to element at index 33 is stored at address 422.

– If array element 0 is stored at address 212, element 5 is stored at 212 + 5 = 217 and element 50 is stored at 212 + 50 = 262.

– Arrays have random access because you can navigate to any index position.• In arrays this navigation can be done

with only one operation!

Advantages of the ArrayListImplementation

Page 45: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 45

• Array data must stored in contiguous memory.

• If we need to expand an array, we don’t know if we’ll have room adjacent to it in memory.

• To expand the array, it must be copied into a new larger array.

• This is extremely costly.

Disadvantages of the ArrayListImplementation

Page 46: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 46

• This is an expensive operation.• The shifted data must be copied to a higher

index in the array.– If the data is added to the the front of the List,

all of the data in the List must be shifted.– Imagine doing this for a List with 5000

elements.• If the array is at max capacity before the add,

the data must also be relocated.• Removing element from the Array can also be

costly for the same reasons.

add(int index, Object element)

Page 47: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 47

• Linked lists don’t allocate memory all at once like an Array list.– It is done incrementally, as needed.

:Student :Student :Student

myClass

null

The other option: LinkedList

Page 48: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 48

• Cannot use simple addition to figure out address of certain element.

• We must go through the List sequentially to find an element– i.e. to get to the element at index 4, we must first go to

element 0, then 1, then 2, then 3, and then 4– Imagine this for a million element list.– Access to a List element can be much slower than an Array

element.• Why would we ever want to use this implementation?

Disadvantages of LinkedList

Page 49: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 49

• Adding an element to a position other than the end of the List can be much more efficient.

• Also true with removing elements• Contains a few extra methods• Which you should use will depend on what

you want to do with the List.

Advantages of LinkedList

Page 50: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 50

• Declare the list like we declare an ArrayListList arrayList = new ArrayList();List linkedList = new LinkedList();

How to Use LinkedList

Page 51: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 51

• If you declared the ArrayList as shown on the previous slide, just replace “new ArrayList()” with “new LinkedList()”

• If you declared the list as follows, then:Arraylist arrayList = new ArrayList();• Method calls that are specific to ArrayList will

become invalid.• Unless you need to use a specific method from

ArrayList or LinkedList you should always declare the list as shown on the previous slide.

• In a similar fashion you can convert code that uses LinkedList to use ArrayList

Converting Code from ArrayList to LinkedList

Page 52: The Java Collections Framework and Lists in Javamarkw/class/cs2334/Lecture Notes/04-JCFa… · • The Java Collections Framework (JCF) includes many ways to manipulate groups of

Page 52

• Chapter 9 Exercises– 10, 12, 13

Sample Exercises