Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
John Hurley Cal State LA
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
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.
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.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
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.
Java's Collection Framework
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
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.
(c) University of Washington14-1 CSC 143 Java 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.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Chapter 18 Java Collections Framework
Computer Science 209 Software Development Java Collections.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
Data structures and algorithms in the collection framework 1.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
16-August-2002cse Libraries © 2002 University of Washington1 Class Libraries CSE 142, Summer 2002 Computer Programming 1
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
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.
University of Limerick1 Collections The Collection Framework.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
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.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Software Development Java Collections
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Java Collections Overview
Introduction to Collections
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Introduction to Collections
Introduction to Collections
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Presentation transcript:

Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet, and TreeSet  List interface, ArrayList, and LinkedList  Vector and Stack  Map, HashMap, and TreeMap  Collection and Array classes

Limitations of arrays F Once an array is created, its size cannot be altered. F Array provides inadequate support for inserting, deleting, sorting, and searching operations.

Java Collection Framework  The java.util package contains some of the most exciting enhancements added by Java2 collections. Collections are a state-of-the-art technology that merits close attention by all Java programmers. F Algorithms is another important part of the collection mechanism. Algorithms operate on collections and are defined as static methods within the Collections class. F Another item created by the collections framework is the Iterator interface. An iterator gives you a general- purpose, standardized way of accessing the elements within a collection, one at a time.

Java Collection Framework F A collection is an object that represents a group of objects, often referred to as elements. F The Java Collections Framework supports two types of collections, named collections and maps.

Java Collection Framework hierarchy, cont.

A collection can be a Set or a List, defined in the interfaces Set and List, which are subinterfaces of Collection interface.

Java Collection Framework hierarchy, cont. An instance of Map represents a group of objects, each of which is associated with a key. You can get the object from a map using a key, and you have to use a key to put the object into the map.

The Collection Interface The Collection interface is the root interface for storing and processing a collection of objects.

The Set Interface F The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. F The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.

The HashSe t Class The HashSet class is a concrete class that implements interface Set. It can be used to store duplicate-free elements.

The Iterator F Iterator is a special object to provide a way to access the elements of a collection sequentially. F Iterator implements one of two interfaces: Iterator or ListIterator

Example: HashSet and Iterator This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list.

Example 19.1 Using HashSet and Iterator import java.util.*; public class TestHashSet { public static void main(String[] args) { Set mySet = new HashSet(); mySet.add(“Red”); mySet.add(“Green”); mySet.add(“White”); mySet.add(“Red”); Iterator iterator = mySet.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next() + “ ”); }

Example 19.1 Using HashSet and Iterator, cont. Iterator iterator = mySet.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next() + “ ”); }... Output: Green Red White F Only one “Red” string is in the set; F The strings are not stored in the order in which they are added. There is no particular order in a hash set.

The SortedSet Interface and the TreeSet Class F SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. F TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order.

The SortedSet Interface and the TreeSet Class, cont. The elements can be sorted in two ways. F One way is to use the Comparable interface. Objects can be compared using by the compareTo() method. This approach is referred to as a natural order. F The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator.

Example 19.2a Using TreeSet to Sort Elements in a Set This example creates a hash set filled with strings, and then creates a tree set for the same strings. The strings are sorted in the tree set using the compareTo() method in the Comparable interface.

Example 19.2a Using TreeSet to Sort Elements in a Set Set hashSet = new HashSet(); hashSet.add(“Yellow”); hashSet.add(“White ”); hashSet.add(“Green”); hashSet.add(“Orange”); System.out.println(“An unsorted set of strings”); System.out.println(hashSet + “\n”);... Output : An unsorted set of strings [Orange, Green, White, Yellow]

Example 19.2a Using TreeSet to Sort Elements in a Set, cont. Set treeSet = new TreeSet(hashSet); System.out.println(“Sorted set of strings”); System.out.println(treeSet + “\n”); Output: A sorted set of strings [Green, Orange, White, Yellow]

Example 19.2b Using TreeSet to Sort Elements in a Set The example also creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. Comparator interface has two methods: public int compare(Object o1, Object o2) public boolean equals(Object o1)

Example:TreeSet to Sort Elements in a Set import java.util.Comparator; public class ShapeComparator implements Comparator { public int compare(Object o1, Object o2) { double area1 = ((Shape)o1).findArea(); double area2 = ((Shape)o2).findArea(); if (area1 < area2) return -1; else if (area1 == area2) return 0; else return 1; }

TreeSet to Sort Elements in a Set Set shapeSet = new TreeSet(new ShapeComparator()); shapeSet.add(new Rectangle(4,5)); shapeSet.add(new Circle(40)); shapeSet.add(new Circle(40)); // one more shapeSet.add(new Cylinder(4,1)); Iterator iterator = shapeSet.iterator(); System.out.println(“A sorted set of shapes”); while(iterator.hasNext()) { Shape object = (Shape)iterator.next()); System.out.println(object + ”, area = “ + object.findAresa()); }

TreeSet to Sort Elements in a Set, cont. Output: A sorted set of strings [Rectangle] width = 4.0, height = 5,0, area = 20.0 [Cylinder] radius = 4.0, length = 1, area = [Circle] radius = 40.0, area =

The List Interface F A set stores non-duplicate elements. To allow duplicate elements to be stored in a collection, you need to use a list. F A list can not only store duplicate elements, but can also allow the user to specify where the element is stored. F The user can access the element by index.

The List Interface, cont.

The List Iterator Extends Iterator, providing two-way sequential access and elements’ modification.

Example 19.3 Using ArrayLis t and LinkedList F This example creates an array list filled with numbers, and inserts new elements into the specified location in the list. F The example also creates a linked list from the array list, inserts and removes the elements from the list. F Finally, the example traverses the list forward and backward.

Example 19.3 Using ArrayLis t and LinkedList ArrayList arrayList = new ArrayList(); // [] arrayList.add(new Integer(1)); //[1] arrayList.add(new Integer(2)); //[1,2] arrayList.add(new Integer(3)); //[1,2,3] arrayList.add(0, new Integer(10)); //[10,1,2,3] arrayList.add(3, new Integer(20)); //[10,1,2,20,3] System.out.println(arrayList); Output: [10,1,2,20,3]

Example 19.3 Using ArrayLis t and LinkedList LinkedList linkedList = new LinkedList(arrayList); linkedList.add(1, “A”); //[10,“A”, 1, 2, 20] linkedList.removeLast(); //[10,“A”, 1, 2] linkedList.addFirst(“B”); //[“B”, 10,“A”, 1, 2] System.out.println(linkedList); Output: [“B”, 10, “A”, 1, 2, 20]

ArrayLis t vs. LinkedList F ArrayList provides support random access through an index without inserting or removing elements from any place other than an end. F LinkedList provides support for random access through an index with inserting and deletion elements from any place. F If your application does not require insertion or deletion of elements, the Array is the most efficient data structure.

The Vector and Stack Classes F The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them are the Vector class and the Stack class. F These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility.

The Vector Class In Java 2, Vector is the same as ArrayList, except that Vector contains the synchronized methods for accessing and modifying the vector. None of the new collection data structures introduced so far are synchronized. If synchronization is required, you can use the synchronized versions of the collection classes. These classes are introduced later in the section, “The Collections Class.”

The Vector Class, cont.

The Stack Class The Stack class represents a last-in-first-out (LIFO) stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack.

Example Using Vector and Stack This example presents two programs to rewrite Example 5.2, using a vector and a stack instead of an array, respectively. The program reads student scores from the keyboard, stores the scores in the vector, finds the best scores, and then assigns grades for all the students. A negative score signals the end of the input. (See the Companion site) AssignGradeUsingVector

The Map Interface The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.

HashMap and TreeMap F The HashMap and TreeMap classes are two concrete implementations of the Map interface. F The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. F The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.

Example 19.5 Using HashMap and TreeMap This example creates a hash map that maps borrowers to mortgages. The program first creates a hash map with the borrower’s name as its key and mortgage as its value. The program then creates a tree map from the hash map, and displays the mappings in ascending order of the keys.

The Collections Class The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read-only collection classes.

Example Using the Collections Class This example demonstrates using the methods in the Collections class. The example creates a list, sorts it, and searches for an element. The example wraps the list into a synchronized and read-only list. (See the Companion site) TestCollections

The Arrays Class The Arrays class contains various static methods for sorting and searching arrays, for comparing arrays, and for filling array elements. It also contains a method for converting an array to a list.

Example Using the Arrays Class This example demonstrates using the methods in the Arrays class. The example creates an array of int values, fills part of the array with 50, sorts it, searches for an element, and compares the array with another array. (See the Companion site) TestArrays