What is Java collections. Java Collections. Interface hierarchy. What is Java collections 12/5/2011. G52APR Application Programming

Similar documents
Class 32: The Java Collections Framework

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

The Java Collections Framework

Data Structures in the Java API

Working with Java Collections

JAVA COLLECTIONS FRAMEWORK

Datastrukturer och standardalgoritmer i Java

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Data Structures and Algorithms

Per imparare a programmare bisogna programmare

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Practical Session 4 Java Collections

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

CMSC 202H. ArrayList, Multidimensional Arrays

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Basic Programming and PC Skills: Basic Programming and PC Skills:

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

D06 PROGRAMMING with JAVA

Java Collections -- List Set Map

Java Map and Set collections

Big O and Limits Abstract Data Types Data Structure Grand Tour.

AP Computer Science Java Mr. Clausen Program 9A, 9B

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Data Structures and Algorithms Lists

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

LINKED DATA STRUCTURES

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Java Coding Practices for Improved Application Performance

dictionary find definition word definition book index find relevant pages term list of page numbers

cs2010: algorithms and data structures

core 2 Basic Java Syntax

Estrutura com iterador-1

Useful Java Collections

Software Development with UML and Java 2 SDJ I2, Spring 2010

Computer. Course Description

Chapter 8: Bags and Sets

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Java Software Structures

Java Interview Questions and Answers

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Lecture 2: Data Structures Steven Skiena. skiena

Efficient Data Structures for Decision Diagrams

Java SE 8 Programming

Loops and ArrayLists

10CS35: Data Structures Using C

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Project 4 DB A Simple database program

Software Engineering Techniques

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

What s Wrong with This?

AP Computer Science AB Syllabus 1

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Ordered Lists and Binary Trees

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Lab Experience 17. Programming Language Translation

Searching Algorithms

4.5 Symbol Table Applications

Database Systems. National Chiao Tung University Chun-Jen Tsai 05/30/2012

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Pseudo code Tutorial and Exercises Teacher s Version

Analysis of a Search Algorithm

Collections and iterators

In this Chapter you ll learn:

Unit 6. Loop statements

Computer Programming I

Object Oriented Software Design

Extreme Computing. Hadoop MapReduce in more detail.

PES Institute of Technology-BSC QUESTION BANK

Introduction to Programming System Design. CSCI 455x (4 Units)

Unordered Linked Lists

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Visualising Java Data Structures as Graphs

Introduction to Object-Oriented Programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Génie Logiciel et Gestion de Projets. Refactoring

Collections Classes for Real-Time and High-Performance Applications. July 4, 2005 Jean-Marie Dautelle

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Health Care Claims System Prototype

Introduction to Parallel Programming and MapReduce

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Building Java Programs

Algorithms and Data Structures Written Exam Proposed SOLUTION

Stacks. Data Structures and Data Types. Collections

Object Oriented Software Design

Data Structures and Algorithms

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

CompSci-61B, Data Structures Final Exam

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

1 of 1 24/05/ :23 AM

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Computer Science III Advanced Placement G/T [AP Computer Science A] Syllabus

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Programming with Data Structures

Transcription:

G52APR Application Programming Java Collections What is Java collections A collection is an object that represents a group of objects Michael Li http://www.cs.nott.ac.uk/~jwl/g52apr.html 2 Interface hierarchy 3 4 What is Java collections A collection is an object that represents a group of objects A number of pre-packaged implementations of common container classes Collections API offers a structured paradigm for manipulating groups of objects in an ordered fashion, and employs design patterns (e.g., the iterator pattern) that make common programming tasks much simpler. 5 6 1

Why use Collections Reduces programming effort Increases performance Provides interoperability between unrelated APIs Reduces the effort required to learn APIs Reduces the effort required to design and implement APIs Fosters software reuse Java Collections Several implementations associated with each of the basic interfaces Each has its own advantages/disadvantages Lists ArrayList, LinkedList Sets HashSet, SortedSet Maps HashMap, SortedMap 7 8 Set and List Set: No duplicate elements permitted. May or may not be ordered. List: A sequence. Duplicates are generally permitted. Map Map: A mapping from keys to objects. Each key can also be an object No duplicate keys permitted The group of keys is a set 9 10 Collections -- classes Concrete classes that implement the interfaces HashSet, SortedSet ArrayList, LinkedList HashMap, SortedMap Create a collection object: Generally hold references to the interface and not the specific class List mylist = new ArrayList(); List otherlist = new ArrayList(5); Map database = new HashMap(); Set things = new HashSet(); Java Collections Adding Items For Sets and Lists, use add() List mylist = new ArrayList(); mylist.add( A String ); mylist.add( Other String ); For Maps, use put() Map mymap = new HashMap(); mymap.put( google, http://www.google.com ); mpmap.put( yahoo, http://www.yahoo.com ); 11 12 2

Java Collections Copying Very easy, just use addall() List mylist = new ArrayList(); //assume we add items to the list List otherlist = new ArrayList(); otherlist.addall(mylist); Collections Getting Individual Items Use get() Note that we have to cast the object to its original type. Sets and Lists String s = (String)myList.get(1); //get first element String s2 = (String)myList.get(10); //get tenth element Maps String s = (String)myMap.get( google ); String s2 = (String)mpMap.get( yahoo ); 13 14 Collections Getting all items For Lists, we could use a for loop, and loop through the list to get() each item But this doesn t work for Maps. To allow generic handling of collections, Java defines an object called an Iterator An object whose function is to walk through a Collection of objects and provide access to each object in sequence 15 Collections Getting all items Get an iterator using the iterator() method Iterator objects have three methods: next() gets the next item in the collection hasnext() tests whether it has reached the end remove() removes the item just returned Basic iterators only go forwards Lists objects have a ListIterator that can go forward and backward 16 Iterator examples Java Collections Set a_set = new HashSet(); Iterator itr = a_set.iterator(); while(itr.hasnext()) { Object element = itr.next(); System.out.print(element + " "); List a_list = new ArrayList(); for(iterator itr = a_list.iterator(); itr.hasnext(); ) { System.out.println( itr.next() ); 17 18 3

Collections Other Functions The java.util.collections class has many useful methods for working with collections min, max, sort, reverse, search, shuffle Virtually all require your objects to implement an extra interface, called Comparable 19 Collections Comparable The Comparable interface labels objects that can be compared to one another. Allows sorting algorithms to be written to work on any kind of object so long as they support this interface Single method to implement public int compareto(object o); Returns A negative number if parameter is less than the object Zero if they re equal A positive number if the parameter is greater than the object 20 Collections Comparator Like Comparable, but is a stand-alone object used for comparing other objects Useful when you want to use your criteria, not that of the implementor of the object. Or altering the behaviour of a system Again has single method: public int compare(object obj1, Object obj2) Comparator Example In this example, String comparison method compareto() is adopted to override compare() public class AlphaComparison implements Comparator { public int compare(object obj1, Object obj2) { String s1 = ((String)o1).toLowerCase(); String s2 = ((String)o2).toLowerCase(); return s1.compareto(s2); 21 22 The Set Interface HashSet and TreeSet The Set interface is used to represent an unordered collection of objects. The two concrete classes in this category are HashSet and TreeSet. A set is in some ways a stripped-down version of a list. Both structures allow you to add and remove elements, but the set form does not offer any notion of index positions. All you can know is whether an object is present or absent from a set. The Collections Framework provides two general purpose implementations of the Set interface: HashSet and TreeSet. The HashSet class is built on the idea of hashing; the TreeSet class is based on a structure called a binary tree. More often than not, you will use a HashSet for storing your duplicate free collection. HashSet allows at most one null element. HashSet is faster than other implementations of Set (TreeSet and LinkedHashSet). The add method of Set returns false if you try to add a duplicate element. The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work properly, elements added to a TreeSet must be sortable 23 24 4

HashSet & TreeSet example import java.util.*; public class SetExample { public static void main(string args[]) { Set set = new HashSet(); set.add("bernadine"); set.add("elizabeth"); set.add("gene"); set.add("elizabeth"); set.add("clara"); System.out.println(set); Set sortedset = new TreeSet(set); System.out.println(sortedSet); Output: [Gene, Clara, Bernadine, Elizabeth] [Bernadine, Clara, Elizabeth, Gene ] Set Operations public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean isempty(); boolean contains(object element); boolean add(e element); boolean remove(object element); Iterator<E> iterator(); // Bulk operations boolean containsall(collection<?> c); boolean addall(collection<? extends E> c); boolean removeall(collection<?> c); boolean retainall(collection<?> c); void clear(); // Array Operations Object[] toarray(); <T> T[] toarray(t[] a); 25 26 The List interface A list is an ordered collection. Lists may contain duplicate elements. List interface includes operations for: Positional access: manipulates elements based on their numerical position in the list Search: searches for a specified object in the list and returns its numerical position Iteration: extends Iterator semantics to take advantage of the list's sequential nature Range-view: performs arbitrary range operations on the list. List Operations public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); boolean add(e element); void add(int index, E element); E remove(int index); boolean addall(int index, Collection<? extends E> c); // Search int indexof(object o); int lastindexof(object o); // Iteration ListIterator<E> listiterator(); ListIterator<E> listiterator(int index); // Range-view List<E> sublist(int from, int to); 27 28 List Iterators List's iterator returns the elements of the list in proper sequence ListIterator allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator. hasnext();next();remove(); previous(); hasprevious(); nextindex(); previousindex(); set(e e); add(e e); 29 List Iterator example List alist = new ArrayList(); alist.add("1"); alist.add("2"); alist.add("3"); alist.add("4"); alist.add("5"); ListIterator itr = alist.listiterator(); System.out.println(listIterator.previousIndex()); System.out.println(listIterator.nextIndex()); listiterator.next(); System.out.println( listiterator.previousindex()); System.out.println( listiterator.nextindex()); Output: -1 0 0 1 30 5

Map interface A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. 31 32 Map Operations The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null. However, you should not add a Map to itself as a key or value. Object put(object key, Object value) Object remove(object key) void putall(map mapping) void clear() Map Operations The query operations allow you to check on the contents of the map: Object get(object key) boolean containskey(object key) boolean containsvalue(object value) int size() boolean isempty() 33 34 Map Operations The last set of methods allow you to work with the group of keys or values as a collection. public Set keyset() public Collection values() public Set entryset() Because the collection of keys in a map must be unique, you get a Set back. Because the collection of values in a map may not be unique, you get a Collection back Map Iteration No direct iteration over Maps Maps do not provide an iterator() method as do Lists and Sets Three indirect ways: iteration over Sets, Collections, or key-value pairs Get a Set of keys by keyset(); Get a Collection of values by values(); Get a Set of key-value pairs entryset(); 35 36 6

Map Iterator example Map Iterator example (II) import java.util.*; public class IterateValuesOfHashMapExample { public static void main(string[] args) { HashMap hmap = new HashMap(); hmap.put("1","one"); hmap.put("2","two"); hmap.put("3","three"); Collection c = hmap.values(); Iterator itr = c.iterator(); while(itr.hasnext()) System.out.println(itr.next()); Output: Three Two One import java.util.*; public class IterateValuesOfHashMapExample { public static void main(string[] args) { Map data = new HashMap(); data.put(ok, "HTTP_OK"); data.put(forbidden, "HTTP_FORBIDDEN"); data.put(not_found, "HTTP_NOT_FOUND"); Set entries = data.entryset(); for(map.entry entry : entries) { Object key = entry.getkey(); Object value = entry.getvalue(); System.out.println(key + " = " + value); Output: OK=HTTP_OK FORBIDDEN=HTTP FORBIDDEN NOT_FOUND=HTTP NOT FOUND 37 38 HashMap & TreeMap The HashMap and TreeMap classes are two concrete implementations of the Map interface. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. With the TreeMap implementation, elements added to the map must be sortable Example: HashMap & TreeMap public class TestMap { public static void main(string[] args) { // Create a HashMap Map hashmap = new HashMap(); hashmap.put("smith", 30); hashmap.put("anderson", 31); hashmap.put("lewis", 29); hashmap.put("cook", 29); System.out.println("Display entries in HashMap"); System.out.println(hashMap); // Create a TreeMap from the previous HashMap Map treemap = new TreeMap(hashMap); System.out.println("\nDisplay entries in ascending order of key"); System.out.println(treeMap); 39 40 Example: HashMap and TreeMap Output: Display entries in HashMap {Smith=30, Lewis=29, Anderson=31, Cook=29 Display entries in ascending order of key {Anderson=31, Cook=29, Lewis=29, Smith=30 Exercise import java.util.*; class HashMapDemo { public static void main(string args[]) { HashMap hm = new HashMap(); hm.put("john Doe", new Double(3434.34)); hm.put("tom Smith", new Double(123.22)); hm.put("jane Baker", new Double(1378.00)); hm.put("todd Hall", new Double(99.22)); TreeMap tm = new TreeMap(hm); System.out.println(tm); Set set = tm.entryset(); Iterator i = set.iterator(); while(i.hasnext()) { System.out.print(i.next() + ": "); System.out.println(tm.get(i.next()); collection col = tm.values(); i = col.iterator(); while(i.hasnext()) { System.out.println(i.next()); 41 42 7

Output {Jane Baker=1378.00, John Doe=3434.34, Todd Hall= 99.22, Tom Smith=123.22 Jane Baker: 3434.34 Todd Hall: 123.22 1378.00 3434.34 99.22 123.22 43 8