Java 2 Collections Bartosz Walter Software Engineering II.

Slides:



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

Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Collections. What is the Collections framework?  Collections framework provides two things: –implementations of common high-level data structures: e.g.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Introduction to Java Collections
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
05 - Containers DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
„Generics and collections”. Generics and collections Generics From JDK They are similar to C++ templates They allow to eliminate runtime exceptions.
The Java Collections Package C. DeJong Fall 2001.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Algorithm Programming Java API and Containers Bar-Ilan University תשס"ח by Moshe Fresko.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections –data structures and Algorithms L. Grewe.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Sadegh Aliakbary Sharif University of Technology Fall 2012.
©SoftMoore ConsultingSlide 1 Java Collections Framework.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
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.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Fundamental of Java Programming
Programming & Data Structures
Data Structures Lakshmish Ramaswamy.
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
Lecture 6: Collections.
Java语言程序设计 马 皓
Introduction to Collections
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
Introduction to Collections
Introduction to Collections
Hashing in java.util
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

Java 2 Collections Bartosz Walter Software Engineering II

Agenda 1.Basic interfaces: Collection, Set, List, Map 2.Iterators 3.Utility classes for Collections and Arrays 4.Special implementations 5.Comparing objects

Java 2 Collections

java.util.Collection  Manages a group of elements  Least common denominator that all collections implement  Imposes no constraints on the elements  No direct implementation General constraints on implementations  Two obligatory constructors:  parameterless Collection()  Collection-based Collection(Collection)

java.util.Collection Groups of methods:  basic operations – adding, removing, measuring  boolean add(Object)  boolean remove(Object)  boolean contains(Object)  boolean isEmpty()  Iterator iterator()  bulk operations – operations on groups of elements  boolean addAll(Collection)  boolean removeAll(Collection)  boolean containsAll(Object)  boolean retainAll()  void clear()  array operations – conversion to arrays  Object[] toArray()  Object[] toArray(Object[])

Java 2 Collections

java.util.List  Subinterface of Collection  Manages a group of ordered elements  Puts some constraints on derivatives  Direct implementations: ArrayList, Vector, LinkedList General constraints on implementations  Positional Access: manipulate elements based on their numerical position in the list.  Search: search for a specified object in the list and return its numerical position.  List Iteration: extend Iterator semantics to take advantage of the list's sequential nature.  Range-view: perform arbitrary range operations on the list.

java.util.List Groups of methods:  positional access  Object get(int)  Object set(int, Object)  Object add(int, Object)  Object remove(int)  search  int indexOf(Object)  int lastIndexOf(Object)  iteration  ListIterator listIterator()  ListIterator listIterator(int)  range view  List subList(int, int)

Java 2 Collections

java.util.Set  Subinterface of Collection, but no new methods (!)  Manages a group of unique elements  Again, puts some constraints on derivatives  Direct implementations: HashSet, TreeSet Collection collection2 = new HashSet(collection);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”); }

Java 2 Collections

java.util.Map  Stores pairs, not single objects  Maps keys to values  Provides Collection views for keys, values and pairs  Cannot contain duplicate keys  Implementations: HashMap, TreeMap, SortedMap General constraints on implementations  Two obligatory constructors:  parameterless Map()  Map-based Map(Map)

java.util.Map Groups of methods:  basic operations  Object put(Object, Object)  Object get(Object)  Object remove(Object)  boolean containsKey(Object)  boolean containsValue(Object)  boolean isEmpty()  int size()  bulk operations  void putAll(Map)  void clear()  Collection views  Set keySet()  Collection values()  Set entrySet()

Example public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); 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:"); System.out.println(m); } > java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1} public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new TreeMap(); 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:"); System.out.println(m); }

Java 2 Collections

java.util.Iterator  Generates a serie of elements, one at a time  Successive calls return successive elements  Replacement for java.util.Enumeration  No publicly available implementation (!)  No public constructor (!)  boolean hasNext()  Object next()  void remove()

Example public class Freq { public static void main(String args[]) { Collection coll = new ArrayList(); for (int i=0; i<args.length; i++) { coll.add(args[i]); } for (Iterator iter = coll.iterator(); iter.hasNext();) String elem = (String) iter.next(); System.out.print(elem + ” ; ”); } > java Freq if it is to be it is up to me to delegate {if; it; is; be; up; is; me; delegate...}

java.util.ListIterator  Subinterface of java.util.Iterator  Works in either direction  No publicly available implementation (!)  No public constructor (!)  void add(Object)  boolean hasPrevious ()  int nextIndex()  Object previous()  int previousIndex()  void set(Object)

Java 2 Collections

Utility classes: java.util.Collections  Binary searching for specific object  Sorting arbitrary List (*)  Copying Lists  Filling Collections with Objects  Finding max and min elements (*)  Reversing a List  Shuffling a List  Swapping two elements

Utility classes: java.util.Collections  int binarySearch(List, Object)  int binarySearch(List, Object, Comparator)  void copy(List, List)  Void fill(List, Object)  Object max/min(Collection)  Object max/min(Collection, Comparator)  List nCopies(int, Object)  void reverse(List)  void shuffle(List)  void sort(List)  void sort(List, Comparator)  void swap(List, int, int)

Task Suggest an implementation of multibag. Bag is a map in that each key maps to multiple values.

Utility classes: java.util.Arrays  Conversion to List  Binary searching for specific object  Equality of two arrays  Filling Arrays with Objects  Sorting Arrays  List asList(Object[])  int binarySearch(type[], type)  int binarySearch(Object[], Object, Comparator)  boolean equals(type[], type[])  void fill(type[], type)  void sort(type[], Comparator)

Wrapping objects: Immutables  Make Collection immutable  Block any mutating methods  No publicly available implementation (!)  No public constructor (!)  Collection unmodifiableCollection(Collection)  Set unmodifiableSet(Set)  List unmodifiableList(List)  Map unmodifiableMap(Map)

Wrapping objects: Synchronization  Make Collection synchronized  Block any mutating methods  No publicly available implementation (!)  No public constructor (!)  Collection synchronizedCollection(Collection)  Set synchronizedSet(Set)  List synchronizedList(List)  Map synchronizedMap(Map)

Wrapping objects: Singletons  Return collection of one specific element  The collection is immutable  No publicly available implementation (!)  No public constructor (!) Remove all instances of element e  c.removeAll(Collections.singleton(e)); Remove all Lawyers from the map:  profession.values().removeAll( Collections.singleton(LAWYER));

Wrapping objects: Empties  Return empty collection  The collection is immutable  Set EMPTY_SET  Collection EMPTY_COLLECTION  Map EMPTY_MAP

Comparing objects: java.lang.Comparable  Sorting, searching requires a method of comparing objects  Comparison can be extracted and plugged as a parameter  Comparable objects can be compared to other objects Sort a List of people by birthday:  Collections.sort(people); public class Person implements Comparable { private name, givenName; //... public int compareTo(Object obj) { } public boolean equals(Object obj) { } public int hashCode() {} }

Comparing objects: java.util.Comparator Sort a List of people by birthday:  Collections.sort(people, comparator); public class Name implements Comparator { public int compare (Object obj1, Object obj2) public boolean equals(Object obj) }  Sorting, searching requires a method of comparing objects  The comparison can be extracted and plugged as a param  Comparators allow for comparing two objects

Comparing objects: java.util.Comparator public class RealComplexComparator implements Comparator { public int compare (Object obj1, Object obj2) { double re1 = ((Complex) obj1).getReal(); double re2 = ((Complex) obj2).getReal(); return (re1 > re2? 1: (re1 == re2? 0: -1); } }

Task Implement sorting a list of Person classes:  using Comparable interface  using Comparator s

Q&A