SD2054 Software Development. The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
The List ADT Textbook Sections
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 19 Java Data Structures
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework (JCF) Introduction and review 1.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures Abstract data types Java classes for Data structures and ADTs.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
AD Lecture #3 Java Collection Framework 1.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
The ArrayList Class An ArrayList is a complex data structure that allows you to add or remove objects from a list and it changes size automatically. The.
CS2110: Software Development Methods
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Web Design & Development Lecture 6
slides created by Marty Stepp and Hélène Martin
Presentation transcript:

SD2054 Software Development

The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!

An array contains no useful pre- defined methods!

Use the classes provided in the Java Collections Framework!

By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class to store a set of objects use the HashMap class to store objects in a map; fix the type of elements within a collection using the generics mechanism; use objects of your own classes in conjunction with Java's collection classes. The Java Collections Framework

The classes in the JCF are all found in the java.util package. import java.util.*

Three important interfaces from this group are: List Set Map

The List interface The List interface specifies the methods required to process an ordered list of objects. Such a list may contain duplicates.

The List interface Two implementations provided : ArrayList & LinkedList

Using an ArrayList to store a queue of jobs waiting for a printer

The ArrayList constructor creates an empty list: ArrayList printQ = new ArrayList();

ArrayList printQ = new ArrayList (); Whats that stuff in angled brackets?

Its a new Java feature called generics! The ArrayList constructor creates an empty list: ArrayList printQ = new ArrayList ();

Use the interface type instead of the implementation type!

List printQ = new ArrayList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List<String> printQIn) { // some code here }

List printQ = new ArrayList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List printQIn) { // some code here }

List printQ = new HashList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List printQIn) { // some code here }

List methods - add printQ.add("myLetter.doc"); myLetter.doc printQ printQ.add("myFoto.jpg"); printQ.add("results.xls"); printQ.add("chapter.doc"); myFoto.jpgresults.xlschapter.doc 0123

List methods - toString All the Java collection types have a toString method defined System.out.println(printQ); Lists are displayed as follows. [myLetter.doc, myFoto.jpg, results.xls, chapter.doc]

List methods – add revisited printQ.add(0, "importantMemo.doc"); printQ myLetter.docmyFoto.jpgresults.xlschapter.doc importantMemo.doc

List methods – set myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc printQ.set(4, "newChapter.doc"); newChapter.doc printQ 01234

List methods – size printQ.set(printQ.size()-1, "newChapter.doc"); myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc newChapter.doc printQ 01234

List methods – indexOf Example: finding myFoto.jpg int index = printQ.indexOf("myFoto.jpg"); if (index != -1) { System.out.println("myFoto.jpg is at index position: " + index); } else { System.out.println("myFoto.jpg not in list"); }

List methods – remove Example : removing "myFoto.jpg" myFoto.jpg myLetter.docimportantMemo.docresults.xlschapter.doc newChapter.doc printQ printQ.remove(2); printQ.remove("myFoto.jpg");

List methods – get System.out.println("First job is " + printQ.get(0)); myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc newChapter.doc printQ First job is importantMemo.doc 01234

List methods – contains if (printQ.contains(poem.doc)) { System.out.println(poem.doc is in the list); } else { System.out.println(poem.doc is not in the list); }

Using the enhanced for loop with collection classes

Example: Iterating through the printQ list to find and display those jobs that end with a.doc extension: for (String item: printQ) { if (item.endsWith(".doc")) { System.out.println(item); } }

The Set interface The Set interface defines the methods required to process a collection of objects in which there is no repetition, and ordering is unimportant.

Which of these are sets? a queue of people waiting to see a doctor:

Which of these are sets? a list of number one records for each of the 52 weeks of a particular year :

Which of these are sets? car registration numbers allocated parking permits. AK346NY QC771OD AZ885JL

There are 2 implementations provided for the Set interface in the JCF. They are HashSet and TreeSet.

Using a HashSet to store a collection of vehicle registration numbers AK346NY QC771OD AZ885JL

The constructor creates an empty set: Set<String> regNums = new HashSet<String>();

Set regNums = new HashSet (); Remember: use the interface type! The constructor creates an empty set:

Set regNums = new HashSet (); Remember: use generics! The constructor creates an empty set:

Set methods - add The add method allows us to insert objects into the set regNums.add(V53PLS); regNums.add(X85ADZ); regNums.add(L22SBG); regNums.add(W79TRV);

Set methods - toString We can display the entire set as follows: System.out.println(regNums); The set is displayed in the same format as a list: [W79TRV, X85ADZ, V53PLS, L22SBG]

Set methods - size As with a list, the size method returns the number of items in the set System.out.println(Number of items in set: + regNums.size() );

Set methods - remove The remove method deletes an item from the set if it is present. regNums.remove(X85ADZ); If we now display the set, the given registration will have been removed: [W79TRV, V53PLS, L22SBG]

Set interface also includes contains & isEmpty methods

Using the enhanced for loop to iterate through a set

The following enhanced for loop will allow us to iterate through the registration numbers and display all registrations after T. for (String item: regNums) { if (item.charAt(0)> 'T') { System.out.println(item); } } [W79TRV, V53PLS, L22SBG] W79TRV V53PLS

Iterator objects

An Iterator object allows the items in a collection to be retrieved by providing three methods defined in the Iterator interface: Methods of the Iterator interface MethodDescriptionInputsOutputs hasNext Returns true if there are more elements in the collection to retrieve and false otherwise. NoneAn item of type boolean. next Retrieves one element from the collection. NoneAn item of the given element type. remove Removes from the collection the element that is currently retrieved None

To obtain an Iterator object from a set, call the iterator method.. Iterator<String> elements = regNums.iterator();

Using an Iterator object with a 'while' loop..

The following removes all registration prior to and including 'T' Iterator<String> elements = regNums.iterator(); while (elements.hasNext()) { String item = elements.next(); if (item.charAt(0)<= 'T') { elements.remove(); } }

The Map interface The Map interface defines the methods required to process a collection consisting of pairs of objects (keys and values) BookISBN

The Map interface The Map interface defines the methods required to process a collection consisting of pairs of objects (keys and values). NH03456 Patient NHS number

The Map interface There are two implementations provided for the Map interface. They are HashMap and TreeMap

Using a HashMap to store a collection of user names and passwords usernamepassword LauraHaliwellmonkey SunaGuventelevision BobbyMannelephant LucyLanemonkey BernardAndersonvelvet

The constructor creates the empty map: Map<String, String> users; users = new HashMap<String, String>( );

Map users; users = new HashMap ( ); Remember: use the interface type!

The constructor creates the empty map: Map users; users = new HashMap ( ); Remember: use generics!

The constructor creates the empty map: Map users; users = new HashMap ( ); KEY type

The constructor creates the empty map: Map users; users = new HashMap ( ); VALUE type

Map methods - put users.put(LauraHaliwell", monkey"); users LauraHaliwell " monkey"

Map methods - put users.put(LauraHaliwell", popcorn"); users LauraHaliwell "monkey"popcorn"

users.put(CharlieSheen", crazy"); users LauraHaliwell "popcorn" Map methods - put CharlieSheen " crazy"

Map methods - containsKey The containsKey method accepts an object and returns true if the object is a key in the map and false otherwise: if (users.containsKey(LauraHaliwell")) { System.out.println(user ID already taken); } There is also a containsValue method to check for the presence of a value in a map.

Map methods - get String password = users.get(LauraHaliwell); if (password != null) { // valid key } else // no such user { System.out.println ("INVALID USERNAME!"); }

Map methods - toString Maps are displayed in the following output: {LauraHaliwell=popcorn, CharlieSheen=crazy, BobbyMann=elephant}

Map methods - remove The remove method accepts a key value and, if the key is present in the map, both the key and value pair are removed: users.remove(LauraHaliwell"); Displaying the map now shows the users ID and password have been removed: {CharlieSheen=crazy, BobbyMann=elephant }

Iterating over the elements of a map In order to scan the items in the map, the keySet method can be used to return the set of keys. Set<String> theKeys = users.keySet(); The set of keys can then be processed in the ways discussed previously for sets.

Using your own classes with Javas collection classes

The constructor creates an empty set: Set<Book> books = new HashSet<Book>();

When storing user-defined objects in any of the JCF collections, these objects should have three specific methods defined: toString equals hashCode

Defining a toString method Here is one possible toString method we could provide for our Book class: public String toString() { return "(" + isbn +", "+ author + ", " + title +")\n"; }

Defining an equals method One possible interpretation of two books being equal is simply that their ISBNs are equal, so the following equals method could be added to the Book class: public boolean equals (Object objIn) { } Book bookIn = objIn; Wrong type!

Defining an equals method public boolean equals (Object objIn) { } Book bookIn = (Book) objIn; return isbn.equals(bookIn.isbn); One possible interpretation of two books being equal is simply that their ISBNs are equal, so the following equals method could be added to the Book class:

The hashCode method The hashCode method returns an integer value from an object. What number can I generate from a book?

The hashCode method The hashCode method returns an integer value from an object. How about using the number of pages!

The hashCode method The hashCode method returns an integer value from an object. 212

The hashCode method The hashCode method returns an integer value from an object. OK, whats the point of this number?

The hashCode method The hashCode method returns an integer value from an object. The number makes it quicker to find items!

The hashCode method

The hashCode method All of Javas predefined classes (such as String) have a meaningful hashCode method defined. For Book equality we check the ISBN only. This ISBN is a String, so all we need to do is to return the hashCode number of this String:

The hashCode method public int hashCode() { return isbn.hashCode(); }