The Java Collections Framework

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

Class 32: The Java Collections Framework

JAVA COLLECTIONS FRAMEWORK

Data Structures in the Java API

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

Datastrukturer och standardalgoritmer i Java

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

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

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

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

Working with Java Collections

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

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

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

Java Map and Set collections

Searching Algorithms

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

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

Java Software Structures

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

CS170 Lab 11 Abstract Data Types & Objects

CMSC 202H. ArrayList, Multidimensional Arrays

Practical Session 4 Java Collections

D06 PROGRAMMING with JAVA

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

Data Structures and Algorithms Lists

Lecture 2: Data Structures Steven Skiena. skiena

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

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

Java Coding Practices for Improved Application Performance

CompSci-61B, Data Structures Final Exam

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

Computer. Course Description

Symbol Tables. Introduction

Useful Java Collections

LINKED DATA STRUCTURES

Visualising Java Data Structures as Graphs

Binary Heap Algorithms

J a v a Quiz (Unit 3, Test 0 Practice)

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

Analysis of a Search Algorithm

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

Ordered Lists and Binary Trees

Contents. 9-1 Copyright (c) N. Afshartous

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

Section IV.1: Recursive Algorithms and Recursion Trees

Sample Questions Csci 1112 A. Bellaachia

CS 111 Classes I 1. Software Organization View to this point:

In this Chapter you ll learn:

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:

Pseudo code Tutorial and Exercises Teacher s Version

Introduction to Parallel Programming and MapReduce

Chapter 8: Bags and Sets

B.Sc (Honours) - Software Development

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

Computer Programming I

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

BCS2B02: OOP Concepts and Data Structures Using C++

Data Structures in Java. Session 15 Instructor: Bert Huang

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

Quick Introduction to Java

Project 4 DB A Simple database program

PA2: Word Cloud (100 Points)

10 Java API, Exceptions, and Collections

COMPUTER SCIENCE. Paper 1 (THEORY)

AP Computer Science Java Subset

Collections and iterators

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

Per imparare a programmare bisogna programmare

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

1 of 1 24/05/ :23 AM

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

core 2 Basic Java Syntax

Building Java Programs

PES Institute of Technology-BSC QUESTION BANK

Data Structures and Algorithms

Programming Languages CIS 443

Advanced Java Client API

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)

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

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

cs2010: algorithms and data structures

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Lecture 9. Semantic Analysis Scoping and Symbol Table

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Lecture 7: Class design for security

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

Graduate Assessment Test (Sample)

Java SE 8 Programming

The Interface Concept

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

Data Structures Using C++ 2E. Chapter 5 Linked Lists

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

10CS35: Data Structures Using C

Basics of Java Programming Input and the Scanner class

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Unordered Linked Lists

4.5 Symbol Table Applications

Transcription:

The Java Collections Framework Definition Set of interfaces, abstract and concrete classes that define common abstract data types in Java e.g. list, stack, queue, set, map Part of the java.util package Implementation Extensive use of generic types, hash codes (Object.hashCode()), and Comparable interface (compareto(), e.g. for sorting) Collection Interface Defines common operations for sets and lists ( unordered ops.) Maps Represented by separate interfaces from list/set (due to key/value relationship vs. a group of elements) - 14 -

Java Collections Interfaces (slide: Carl Reynolds) Note: Some of the material on these slides was taken from the Java Tutorial at http://www.java.sun.com/docs/books/tutorial - 15 -

- 16 -

Implementation Classes (slide derived from: Carl Reynolds) Interface Implementation Set HashSet TreeSet LinkedHashSet List ArrayList LinkedList Map HashMap TreeMap LinkedHashMap Note: When writing programs use the interfaces rather than the implementation classes where you can: this makes it easier to change implementations of an ADT. - 17 -

Notes on Unordered Collections (Set, Map Implementations) HashMap, HashSet Hash table implementation of set/map Use hash codes (integer values) to determine where set elements or (key,value) pairs are stored in the hash table (array) LinkedHashMap, LinkedHashSet Provide support for arranging set elements or (key,value) pairs by order of insertion by adding a linked list within the hash table elements TreeMap,TreeSet Use binary search tree implementations to order set elements by value, or (key,value) pairs by key value - 18 -

Sets in the Collections Framework E: a generic type parameter - 19 -

E: a generic type parameter - 20 -

HashSet (Example: TestHashSet.java, Liang) Methods: Except for constructors, defined methods identical to Collection Element Storage: Unordered, but stored in a hash table according to their hash codes **All elements are unique Do not expect to see elements in the order you add them when you output them using tostring(). Hash Codes Most classes in Java API override the hashcode() method in the Object class Need to be defined to properly disperse set elements in storage (i.e. throughout locations of the hash table) For two equivalent objects, hash codes must be the same - 21 -

LinkedHashSet (example: TestLinkedHashSet.java) Methods Again, same as Collection Interface except for constructors Addition to HashSet Elements in hash table contain an extra field defining order in which elements are added (as a linked list) List maintained by the class Hash Codes Notes from previous slide still apply (e.g. equivalent objects, equivalent hash codes) - 22 -

Ordered Sets: TreeSet (example: TestTreeSet.java) Methods Add methods from SortedSet interface: first(), last(), headset(toelement: E), tailset(fromelement: E) Implementation A binary search tree, such that either: 1. Objects (elements) implement the Comparable interface (compareto() ) ( natural order of objects in a class), or 2. TreeSet is constructed using an object implementing the Comparator interface (compare()) to determine the ordering (permits comparing objects of the same or different classes, create different orderings) One of these will determine the ordering of elements. Notes It is faster to use a hash set to retrieve elements, as TreeSet keeps elements in a sorted order (making search necessary) Can construct a tree set using an existing collection (e.g. a hash set) - 23 -

Iterator Interface Purpose Provides uniform way to traverse sets and lists Instance of Iterator given by iterator() method in Collection Operations Similar behaviour to operations used in Scanner to obtain a sequence of tokens Check if all elements have been visited (hasnext()) Get next element in order imposed by the iterator (next()) remove() the last element returned by next() - 24 -

List Interface (modified slide from Carl Reynolds) // Positional Access get(int):e; set(int,e):e; add(int, E):void; remove(int index):e; addall(int, Collection):boolean; // Search int indexof(e); int lastindexof(e); List<E> // Iteration listiterator():listiterator<e>; listiterator(int):listiterator<e>; // Range-view List sublist(int, int):list<e>; - 25 -

ListIterator (modified slide from Carl Reynolds) the ListIterator interface extends Iterator Forward and reverse directions are possible ListIterator is available for Java Lists, such as the LinkedList implementation ListIterator <E> hasnext():boolean; next():e; hasprevious():boolean; previous(): E; nextindex(): int; previousindex(): int; remove():void; set(e o): void; add(e o): void; - 26 -

The Collections Class Operations for Manipulating Collections Includes static operations for sorting, searching, replacing elements, finding max/min element, and to copy and alter collections in various ways. (using this in lab5) Note! Collection is an interface for an abstract data type, Collections is a separate class for methods operating on collections. - 27 -

List: Example TestArrayAndLinkedList.java (course web page) - 28 -

Map <K,V> Interface (modified slide from Carl Reynolds) Map <K,V> // Basic Operations put(k, V):V; get(k):v; remove(k):v; containskey(k):boolean; containsvalue(v):boolean; size():int; isempty():boolean; Entry <K,V> getkey():k; getvalue():v; setvalue(v):v; // Bulk Operations void putall(map t):void; void clear():void; // Collection Views keyset():set<k>; values():collection<v>; entryset():set<entry<k,v>>; - 29 -

Map Examples CountOccurranceOfWords.java (course web page) TestMap.java (from text) - 30 -

Comparator Interface (a generic class similar to Comparable) (comparator slides adapted from Carl Reynolds) You may define an alternate ordering for objects of a class using objects implementing the Comparator Interface (i.e. rather than using compareto()) Sort people by age instead of name Sort cars by year instead of Make and Model Sort clients by city instead of name Sort words alphabetically regardless of case - 31 -

Comparator<T> Interface One method: compare( T o1, T o2 ) Returns: negative if o1 < o2 Zero if o1 == o2 positive if o1 > o2-32 -

Example Comparator: Compare 2 Strings regardless of case import java.util.*; public class CaseInsensitiveComparator implements Comparator<String> { public int compare( String stringone, String stringtwo ) { } } // Shift both strings to lower case, and then use the // usual String instance method compareto() return stringone.tolowercase().compareto( stringtwo.tolowercase() ); - 33 -

Using a Comparator... Collections.sort( mylist, mycomparator ); Collections.max( mycollection, mycomparator ); Set mytree = new TreeSet<String>( mycomparator ); Map mymap = new TreeMap<String>( mycomparator ); import java.util.*; public class SortExample2B { public static void main( String args[] ) { List alist = new ArrayList<String>(); } } for ( int i = 0; i < args.length; i++ ) { alist.add( args[ i ] ); } Collections.sort( alist, new CaseInsensitiveComparator() ); System.out.println( alist ); - 34 -

...