Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Similar documents
Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Generics Collection Framework

CONTAİNERS COLLECTİONS

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Sets and Maps. Part of the Collections Framework

CSC 1214: Object-Oriented Programming

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

CS Ananda Gunawardena

Lecture 6 Collections

9/16/2010 CS Ananda Gunawardena

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

What is the Java Collections Framework?

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Class 32: The Java Collections Framework

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Java Collections Framework: Interfaces

A simple map: Hashtable

Java Collections Framework reloaded

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

An Interface with Generics

Collections (Java) Collections Framework

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Generics and collections

Tha Java Programming Language

Algorithms. Produced by. Eamonn de Leastar

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

DM550 Introduction to Programming part 2. Jan Baumbach.

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Appendix A: Interfaces and Classes in the AP Java Subset (AB)

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

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

Collections Framework: Part 2

DM550 Introduction to Programming part 2. Jan Baumbach.

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Generic classes & the Java Collections Framework. *Really* Reusable Code

Java collections framework

Introduction to Collections

COMP6700/2140 Abstract Data Types: Queue, Set, Map

Object-Oriented Programming with Java

CS11 Java. Winter Lecture 8

Collections. The Java Collections Framework. The Interfaces

CMSC 202H. Containers and Iterators

Collections Questions

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

Software 1 with Java. Recitation No. 6 (Collections)

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Java collections framework

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

The Java Collections Framework. Chapters 7.5

Java Collection Framework

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

An Introduction to Data Structures

Collections. OOP encapsulates data inside classes, but this doesn t make how you

Collections. Collections. Collections - Arrays. Collections - Arrays

CS2110: Software Development Methods. Maps and Sets in Java

CISC 3115 TY3. C24a: Lists. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/15/2018 CUNY Brooklyn College

CSE 143 Au03 Final Exam Page 1 of 15

Lecture 4. The Java Collections Framework

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

CSE 143 Au03 Midterm 2 Page 1 of 7

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

EXAMINATIONS 2016 TRIMESTER 2

JAVA. java.lang.stringbuffer java.lang.stringbuilder

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

SSJ User s Guide. Package simevents Simulation Clock and Event List Management

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Lecture 16: Case Study: The Java Collections API

Introduction to Computer Science I

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

Lists Chapters Linked Lists Abstract Implementations Storage Leaks Ordered Lists

CS 307 Final Spring 2008

Collections and Maps

Java Collections Framework. 24 April 2013 OSU CSE 1

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

Interfaces, collections and comparisons

Basicsof programming3. Java collections

Transcription:

Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/ 3-February-2003 cse403-10-collections 2003 University of Washington 1 3-February-2003 cse403-10-collections 2003 University of Washington 2 Java 2 Collections A collection is an object that groups multiple elements into a single unit Very useful» store, retrieve and manipulate data» transmit data from one method to another» data structures and methods written by hotshots in the field Joshua Bloch, who also wrote the Collections tutorial Collections Framework Unified architecture for representing and manipulating collections. A collections framework contains three things» Interfaces» Implementations» Algorithms 3-February-2003 cse403-10-collections 2003 University of Washington 3 3-February-2003 cse403-10-collections 2003 University of Washington 4

Collections Framework Diagram Collection Interface Interfaces, Implementations, and Algorithms From Thinking in Java, page 462 Defines fundamental methods» int size();» boolean isempty();» boolean contains(object element);» boolean add(object element); // Optional» boolean remove(object element); // Optional» Iterator iterator(); These methods are enough to define the basic behavior of a collection Provides an Iterator to step through the elements in the Collection 3-February-2003 cse403-10-collections 2003 University of Washington 5 3-February-2003 cse403-10-collections 2003 University of Washington 6 Iterator Interface Iterator Position Defines three fundamental methods» Object next()» boolean hasnext()» void remove() These three methods provide access to the contents of the collection An Iterator knows position within collection Each call to next() reads an element from the collection» Then you can use it or remove it 3-February-2003 cse403-10-collections 2003 University of Washington 7 3-February-2003 cse403-10-collections 2003 University of Washington 8

Example - SimpleCollection List Interface Context public class SimpleCollection { public static void main(string[] args) { Collection c; c = new ArrayList(); System.out.println(c.getClass().getName()); for (int i=1; i <= 10; i++) { c.add(i + " * " + i + " = "+i*i); Iterator iter = c.iterator(); while (iter.hasnext()) System.out.println(iter.next()); Collection List 3-February-2003 cse403-10-collections 2003 University of Washington 9 3-February-2003 cse403-10-collections 2003 University of Washington 10 List Interface The List interface adds the notion of order to a collection The user of a list has control over where an element is added in the collection Lists typically allow duplicate elements Provides a ListIterator to step through the elements in the list. ListIterator Interface Extends the Iterator interface Defines three fundamental methods» void add(object o) - before current position» boolean hasprevious()» Object previous() The addition of these three methods defines the basic behavior of an ordered list A ListIterator knows position within list 3-February-2003 cse403-10-collections 2003 University of Washington 11 3-February-2003 cse403-10-collections 2003 University of Washington 12

Iterator Position - next(), previous() ArrayList and LinkedList Context Collection List ArrayList LinkedList 3-February-2003 cse403-10-collections 2003 University of Washington 13 3-February-2003 cse403-10-collections 2003 University of Washington 14 List Implementations ArrayList» low cost random access» high cost insert and delete» array that resizes if need be LinkedList» sequential access» low cost insert and delete» high cost random access ArrayList overview Constant time positional access (it s an array) One tuning parameter, the initial capacity public ArrayList(int initialcapacity) { super(); if (initialcapacity < 0) throw new IllegalArgumentException( "Illegal Capacity: "+initialcapacity); this.elementdata = new Object[initialCapacity]; 3-February-2003 cse403-10-collections 2003 University of Washington 15 3-February-2003 cse403-10-collections 2003 University of Washington 16

ArrayList methods The indexed get and set methods of the List interface are appropriate to use since ArrayLists are backed by an array» Object get(int index)» Object set(int index, Object element) Indexed add and remove are provided, but can be costly if used frequently» void add(int index, Object element)» Object remove(int index) May want to resize in one shot if adding many elements» void ensurecapacity(int mincapacity) LinkedList overview Stores each element in a node Each node stores a link to the next and previous nodes Insertion and removal are inexpensive» just update the links in the surrounding nodes Linear traversal is inexpensive Random access is expensive» Start from beginning or end and traverse each node while counting 3-February-2003 cse403-10-collections 2003 University of Washington 17 3-February-2003 cse403-10-collections 2003 University of Washington 18 private static class Entry { Object element; Entry next; Entry previous; LinkedList entries Entry(Object element, Entry next, Entry previous) { this.element = element; this.next = next; this.previous = previous; private Entry header = new Entry(null, null, null); public LinkedList() { header.next = header.previous = header; 3-February-2003 cse403-10-collections 2003 University of Washington 19 LinkedList methods The list is sequential, so access it that way» ListIterator listiterator() ListIterator knows about position» use add() from ListIterator to add at a position» use remove() from ListIterator to remove at a position LinkedList knows a few things too» void addfirst(object o), void addlast(object o)» Object getfirst(), Object getlast()» Object removefirst(), Object removelast() 3-February-2003 cse403-10-collections 2003 University of Washington 20

Set Interface Context Set Interface Collection Set Same methods as Collection» different contract - no duplicate entries Defines two fundamental methods» boolean add(object o) - reject duplicates» Iterator iterator() Provides an Iterator to step through the elements in the Set» No guaranteed order in the basic Set interface» There is a SortedSet interface that extends Set 3-February-2003 cse403-10-collections 2003 University of Washington 21 3-February-2003 cse403-10-collections 2003 University of Washington 22 HashSet and TreeSet Context Collection Set HashSet TreeSet 3-February-2003 cse403-10-collections 2003 University of Washington 23 HashSet Find and add elements very quickly» uses hashing implementation in HashMap Hashing uses an array of linked lists» The hashcode() is used to index into the array» Then equals() is used to determine if element is in the (short) list of elements at that index No order imposed on elements The hashcode() method and the equals() method must be compatible» if two objects are equal, they must have the same hashcode() value 3-February-2003 cse403-10-collections 2003 University of Washington 24

TreeSet Elements can be inserted in any order The TreeSet stores them in order» Red-Black Trees out of Cormen-Leiserson-Rivest An iterator always presents them in order Default order is defined by natural order» objects implement the Comparable interface» TreeSet uses compareto(object o) to sort Can use a different Comparator» provide Comparator to the TreeSet constructor Map Interface Context Map 3-February-2003 cse403-10-collections 2003 University of Washington 25 3-February-2003 cse403-10-collections 2003 University of Washington 26 Map Interface Stores key/value pairs Maps from the key to the value Keys are unique» a single key only appears once in the Map» a key can map to only one value Values do not have to be unique Map methods Object put(object key, Object value) Object get(object key) Object remove(object key) boolean containskey(object key) boolean containsvalue(object value) int size() boolean isempty() 3-February-2003 cse403-10-collections 2003 University of Washington 27 3-February-2003 cse403-10-collections 2003 University of Washington 28

Map views A means of iterating over the keys and values in a Map Set keyset()» returns the Set of keys contained in the Map Collection values()» returns the Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. Set entryset()» returns the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set. 3-February-2003 cse403-10-collections 2003 University of Washington 29 HashMap and TreeMap Context Map HashMap TreeMap 3-February-2003 cse403-10-collections 2003 University of Washington 30 HashMap and TreeMap HashMap» The keys are a set - unique, unordered»fast TreeMap» The keys are a set - unique, ordered» Same options for ordering as a TreeSet Natural order (Comparable, compareto(object)) Special order (Comparator, compare(object, Object)) 3-February-2003 cse403-10-collections 2003 University of Washington 31 Bulk Operations In addition to the basic operations, a Collection may provide bulk operations boolean containsall(collection c); boolean addall(collection c); // Optional boolean removeall(collection c); // Optional boolean retainall(collection c); // Optional void clear(); // Optional Object[] toarray(); Object[] toarray(object a[]); 3-February-2003 cse403-10-collections 2003 University of Washington 32

Utilities Context Utilities The Collections class provides a number of static methods for fundamental algorithms Most operate on Lists, some on all Collections» Sort, Search, Shuffle» Reverse, fill, copy» Min, max Wrappers» synchronized Collections, Lists, Sets, etc» unmodifiable Collections, Lists, Sets, etc 3-February-2003 cse403-10-collections 2003 University of Washington 33 3-February-2003 cse403-10-collections 2003 University of Washington 34 Appendix Legacy classes Still available Don t use for new development» unless you have to, eg, J2ME, J2EE in some cases Retrofitted into Collections framework Hashtable» use HashMap Enumeration» use Collections and Iterators» if needed, can get an Enumeration with Collections.enumeration(Collection c) 3-February-2003 cse403-10-collections 2003 University of Washington 35 3-February-2003 cse403-10-collections 2003 University of Washington 36

Vector» use ArrayList Stack» use LinkedList More Legacy classes BitSet» use ArrayList of boolean, unless you can t stand the thought of the wasted space Properties» legacies are sometimes hard to walk away from» see next few pages Properties class Located in java.util package Special case of Hashtable» Keys and values are Strings» Tables can be saved to/loaded from file 3-February-2003 cse403-10-collections 2003 University of Washington 37 3-February-2003 cse403-10-collections 2003 University of Washington 38 System properties Java VM maintains set of properties that define system environment» Set when VM is initialized» Includes information about current user, VM version, Java environment, and OS configuration Properties prop = System.getProperties(); Enumeration e = prop.propertynames(); while (e.hasmoreelements()) { String key = (String) e.nextelement(); System.out.println(key + " value is " + prop.getproperty(key)); 3-February-2003 cse403-10-collections 2003 University of Washington 39