CS Ananda Gunawardena

Similar documents
9/16/2010 CS Ananda Gunawardena

CONTAİNERS COLLECTİONS

Sets and Maps. Part of the Collections Framework

What is the Java Collections Framework?

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

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

Java Collections Framework: Interfaces

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

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

Generics Collection Framework

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

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.

Class 32: The Java Collections Framework

CSC 1214: Object-Oriented Programming

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

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

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

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

Masyvai Javoje. Masyvai. Objektų talpyklos. Masyvo tipas. Deklaravimo pavyzdžiai. Deklaracija ir sukūrimas. Masyvo superklas - Object

Introduction to Collections

Collections. The Java Collections Framework. The Interfaces

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

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Lecture 6 Collections

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

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

Java Collection Framework

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

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

Generic Programming. *Really* reusable code

Generics and collections

Algorithms. Produced by. Eamonn de Leastar

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Collections. Other references:

An Interface with Generics

List... NOTE We use List as illustrative example of collections Study the others from textbook!

CMSC 202H. Containers and Iterators

A simple map: Hashtable

Tha Java Programming Language

Java collections framework

CMSC 202. Containers

Java collections framework

EECS 2011 M: Fundamentals of Data Structures

Collections and Maps

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

Interfaces, collections and comparisons

# $ $ A.A. 2006/07 Tutor: Daniele Tiles &== %% & '( ) * + $, $ $ -' %./, $ * $ $ 7 5 &7 2$ $ $ 3&4&&& 5 +8$ 9%:

Data Structures and Algorithms

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS S-05 Abstract Data Types and Lists 1

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.

CSE 143 Au03 Midterm 2 Page 1 of 7

The Java Collections Framework. Chapters 7.5

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

Collections (Java) Collections Framework

PIC 20A Collections and Data Structures

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

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

CS2110: Software Development Methods. Maps and Sets in Java

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

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

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

ArrayList. Introduction. java.util.arraylist

CS2110: Software Development Methods. Maps and Sets in Java

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Basicsof programming3. Java collections

Collections Framework: Part 2

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

Charlie Garrod Bogdan Vasilescu

11. Collections of Objects

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

CSE 143 Au03 Midterm 2 Sample Solution Page 1 of 7

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

Computer Science II (Spring )

Lecture 4. The Java Collections Framework

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

Framework in Java 5. DAAD project Joint Course on OOP using Java

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

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

Collections of Objects. Object Oriented Programming Camilo López

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

EXAMINATIONS 2016 TRIMESTER 2

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

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Generic Collections CSC Spring 2019 Howard Rosenthal

JAVA COLLECTION FRAMEWORK & SETS

Hash Table. Ric Glassey

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

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Object-Oriented Programming in the Java language

EXAMINATIONS 2017 TRIMESTER 2

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

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

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

13 A: External Algorithms II; Disjoint Sets; Java API Support

Transcription:

CS 15-121 Ananda Gunawardena

A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another. Examples: Arrays, hashtables, vector, set, map, tree

ArrayList is a java collection that allows management of a dynamic list collection Eg: ArrayList A = new ArrayList(); A.add(new Integer(10)); System.out.println(A.get(0)); If (A.contains(new Integer(10))) {.} A.remove(0);

See others at http://java.sun.com/j2se/1.4.2/docs/api/java/util/arraylist.html

Given an ArrayList A of objects write a method removedups that removes all duplicate elements from the list

The Collections Framework A unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. Reduces programming effort while increasing performance. Allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse.

Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy. Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality.

A Java interface contains specifications for a known set of functions. These functions are to be implemented by classes Eg: public class foo implements List { } Interfaces from java collections framework

Java does not allow above Here is a hack

Reduces programming effort Increases program speed and quality Allows interoperability among unrelated APIs Reduces the effort to learn and use new APIs: Reduces effort to design new APIs Supports software reuse

Set is a collection with NO order Similar to the Mathematical Abstraction of Set public interface Set { // Basic Operations int size(); boolean isempty(); boolean contains(object element); boolean add(object element); // Optional boolean remove(object element); Iterator iterator(); boolean removeall(collection c); boolean retainall(collection c); void clear(); // Bulk Operations boolean containsall(collection c); boolean addall(collection c); //Array Operations Object[] toarray(); Object[] toarray(object a[]); } Example: Collections nodups = new HashSet(c );

import java.util.*; public class FindDups { public static void main(string args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: "+args[i]); System.out.println(s.size()+" distinct words detected: "+s); } } What is the output of : java FindDups I am sam sam I am

s1.containsall(s2): Returns true if s2 is a subset of s1 s1.addall(s2): Transforms s1 into the union of s1 and s2 s1.retainall(s2): Transforms s1 into the intersection of s1 and s2 s1.removeall(s2): Transforms s1 into the (asymmetric) set difference of s1 and s2 Exercise: Write a program that will read a line of words and list those ones that occur once and those that occur more than once. Example: java FindDups i am Sam Sam I am Unique words: [i, I ] Duplicate words: [Sam, am] More info at: http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html

List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for: Index based Access: manipulate elements based on their numerical position in the list. Search: search for a specified object in the list and return its index position. List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. Range-view: perform arbitrary range operations on the list.

public interface List extends Collection { // index based Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); Object remove(int index); abstract boolean addall(int index, Collection c); // Search int indexof(object o); int lastindexof(object o); ListIterator listiterator(); ListIterator listiterator(int index); // Range-view List sublist(int from, int to); }

Two important List implementations ArrayList LinkedList

Iterators allow collection to be accessed using a pre-defined pointer public interface ListIterator extends Iterator { boolean hasnext(); Object next(); boolean hasprevious(); Object previous(); int nextindex(); int previousindex(); void remove(); // Optional void set(object o); void add(object o); }

What is the purpose of the following code? for (ListIterator i=l.listiterator(l.size()); i.hasprevious(); ) { Foo f = (Foo) i.previous();... } Steps through a list backwards

Maps keys to values Each Key can map to a unique value public interface Map { // Basic Operations 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(); // Bulk Operations void putall(map t); void clear(); // Collection Views public Set keyset(); public Collection values(); public Set entryset(); // Interface for entryset elements public interface Entry { Object getkey(); Object getvalue(); Object setvalue(object value); } }

HashTable is an implementation of the Map interface An example of generating a frequency table import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(string args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+" distinct words detected:"); System.out.println(m); } }

The Java provides a reusable algorithms that can operate on a List. The following algorithms are provided. Sorting Shuffling Routine Data Manipulation Searching Composition Finding Extreme Values

A List can be sorted according to its natural ordering Java uses an optimized merge sort Fast: runs in n log(n) time Runs faster on nearly sorted lists. Stable: It doesn't reorder equal elements.

import java.util.*; public class Sort { public static void main(string[] args) { List list = new ArrayList(); list.add( guna ); list.add( bob ); //etc Collections.sort(list); System.out.println(list); }

Shuffle algorithm does the opposite of sort It puts elements in the list in a random order so that each element is equally likely Applications Shuffle a card deck Example: Collections.shuffle(list);

Reverse reverses the order of the elements in a List. Fill overwrites every element in a List with the specified value. This operation is useful for reinitializing a List. Copy takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected. Swap swaps the elements at the specified positions in a List. addall adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array. Source: java.sun.com

The binary search algorithm provides a way to search for a key. Example int pos = Collections.binarySearch(list, key); if (pos < 0) l.add(-pos-1);

Frequency counts the number of times the specified element occurs in the specified collection Disjoint determines whether two Collections are disjoint; that is, whether they contain no elements in common