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.

Slides:



Advertisements
Similar presentations
Queues Printer queues Several jobs submitted to printer Jobs form a queue Jobs processed in same order as they were received.
Advertisements

Why not just use Arrays? Java ArrayLists.
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.
SD2054 Software Development. The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!
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;
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++)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
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™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
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.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
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.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
18-1 Queues Data Structures and Design with Java and JUnit © Rick Mercer.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
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.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
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.
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.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
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
Linked Data Structures
Slides by Donald W. Smith
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
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.
CSE 143 Lecture 27: Advanced List Implementation
Object Oriented Programming in java
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:

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; fix the type of elements within a collection using the generics mechanism; use an Iterator object to scan through a collection;

The Limitation of Arrays An array is a very useful type in Java but it has its restrictions: once an array is created it must be sized, and this size is fixed; it contains no useful pre-defined methods. Java comes with a group of generic collection classes that grow as more elements are added to them, and these classes provide lots of useful methods. This group of collection classes are referred to as the Java Collections Framework.

JCF Interfaces The classes in the JCF are all found in the java.util package. 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. Examples of a list of objects: jobs waiting for a printer, emergency calls waiting for an ambulance the names of players that have won the Wimbledon tennis tournament over the last 10 years. There are two implementations provided for the List interface in the JCF. They are ArrayList and LinkedList

Using an ArrayList to store a queue of jobs waiting for a printer We will represent these jobs by a series of Job ID Strings. The ArrayList constructor creates an empty list: ArrayList<String> printQ = new ArrayList<String>(); The stuff in angled brackets is a new feature introduced in Java 5 called generics.

Using the interface type instead of the implementation type Better to declare collection objects to be the type of the interface rather than the type of the class that implements this collection. ArrayList printQ = new ArrayList ();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 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 So we can display the entire list to the screen 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 Lists provide a size method to return the number of items in the list printQ.set(printQ.size()-1, "newChapter.doc"); myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc newChapter.doc printQ So we could have renamed the last job in the queue in the following way also: 01234

List methods – indexOf The indexOf method returns the index of the first occurrence of a given object within the list. It returns -1 if the object is not in the list. 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 Items can be removed either by specifying an index or an object. When an item is removed, items behind this item shuffle to the left Example : removing "myFoto.jpg" myFoto.jpg myLetter.docimportantMemo.docresults.xlschapter.doc newChapter.doc printQ printQ.remove(2); printQ.remove("myFoto.jpg");

List methods – get The get method allows a particular item to be retrieved from the list via its index position. The following displays the job at the head of the queue 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 The contains method can be used to check whether or not a particular item is present in the list: 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 The enhanced for loop can be used with the List (and Set ) implementations provided in the JCF. For example, here an enhanced for loop is used to iterate 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; a list of number one records for each of the 52 weeks of a particular year; car registration numbers allocated parking permits.    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 The constructor creates an empty set: Set<String> regNums = new HashSet<String>(); we have used the generics mechanism to indicate that this is a set of String objects, and we have given the type of this object as the interface 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 and 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, the iterator method is called.

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(); } }