SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Downloaden Sie, um offline zu lesen
Java Collection Framework
Version March 2009
2
Framework
 Interfaces (ADT, Abstract Data Types)
 Implementations (of ADT)
 Algorithms (sort)
 java.util.*
 Java 5 released!
 Lots of changes about collections
3
Interfaces
Collection<E>
Set<E> List<E>
Map<K,V>
SortedSet<E>
SortedMap<K,V>
Group containers
Associative containers
Queue<E>
Iterable<E>
4
Implementations
TreeSet
TreeMapArray
List
Linked
List
HashMap
Linked
HashMap
Linked
HashSet
HashSet
Map<K,V>
Sorted
Map<K,V>
Collection<E>
Set<E> List<E>
Sorted
Set<E>
Queue<E>
Priority
Queue
5
Internals
LinkedList
Linked list
LinkedHashMapTreeMapHashMapMap
ArrayListList
LinkedHashSetTreeSetHashSetSet
Hash table
Linked list
Balanced
tree
Resizable
array
Hash
table
interface
data structure
classes
6
Collection
 Group of elements (references to objects)
 It is not specified whether they are
 Ordered / not ordered
 Duplicated / not duplicated
 Following constructors are common to all
classes implementing Collection
 T()
 T(Collection c)
7
Collection interface
 int size()
 boolean isEmpty()
 boolean contains(Object element)
 boolean containsAll(Collection c)
 boolean add(Object element)
 boolean addAll(Collection c)
 boolean remove(Object element)
 boolean removeAll(Collection c)
 void clear()
 Object[] toArray()
 Iterator iterator()
8
Collection example
Collection<Person> persons =
new LinkedList<Person>();
persons.add( new Person(“Alice”) );
System.out.println( persons.size() );
Collection<Person> copy =
new TreeSet<Person>();
copy.addAll(persons);//new TreeSet(persons)
Person[] array = copy.toArray();
System.out.println( array[0] );
9
Map
 An object that associates keys to values
(e.g., SSN ⇒ Person)
 Keys and values must be objects
 Keys must be unique
 Only one value per key
 Following constructors are common to all
collection implementers
 T()
 T(Map m)
10
Map interface
 Object put(Object key, Object value)
 Object get(Object key)
 Object remove(Object key)
 boolean containsKey(Object key)
 boolean containsValue(Object value)
 public Set keySet()
 public Collection values()
 int size()
 boolean isEmpty()
 void clear()
11
Map example
Map<String,Person> people =
new HashMap<String,Person>();
people.put( “ALCSMT”, //ssn
new Person(“Alice”, “Smith”) );
people.put( “RBTGRN”, //ssn
new Person(“Robert”, “Green”) );
Person bob = people.get(“RBTGRN”);
if( bob == null )
System.out.println( “Not found” );
int populationSize = people.size();
12
Generic collections
 From Java 5, all collection interfaces
and classes have been redefined as
Generics
 Use of generics lead to code that is
 safer
 more compact
 easier to understand
 equally performing
13
Generic list - excerpt
public interface List<E>{
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}
14
Example
Using a list of Integers
 Without generics ( ArrayList list )
list.add(0, new Integer(42));
int n= ((Integer)(list.get(0))).intValue();
 With generics ( ArrayList<Integer> list )
list.add(0, new Integer(42));
int n= ((Integer)(list.get(0))).intValue();
 + autoboxing ( ArrayList<Integer> list )
list.add(0,new Integer(42));
int total = list.get(0).intValue();
Group containers
(Collections) Collection<E>
Set<E> List<E>
SortedSet<E>
Queue<E>
16
List
 Can contain duplicate elements
 Insertion order is preserved
 User can define insertion point
 Elements can be accessed by position
 Augments Collection interface
17
List additional methods
 Object get(int index)
 Object set(int index, Object element)
 void add(int index, Object element)
 Object remove(int index)
 boolean addAll(int index, Collection c)
 int indexOf(Object o)
 int lastIndexOf(Object o)
 List subList(int fromIndex, int toIndex)
18
List implementations
ArrayList
 get(n)
 Constant time
 Insert (beginning)
and delete while
iterating
 Linear
LinkedList
 get(n)
 Linear time
 Insert (beginning)
and delete while
iterating
 Constant
19
List implementations
 ArrayList
 ArrayList()
 ArrayList(int initialCapacity)
 ArrayList(Collection c)
 void ensureCapacity(int minCapacity)
 LinkedList
 void addFirst(Object o)
 void addLast(Object o)
 Object getFirst()
 Object getLast()
 Object removeFirst()
 Object removeLast()
20
Example I
LinkedList<Integer> ll =
new LinkedList<Integer>();
ll.add(new Integer(10));
ll.add(new Integer(11));
ll.addLast(new Integer(13));
ll.addFirst(new Integer(20));
//20, 10, 11, 13
21
Example II
Car[] garage = new Car[20];
garage[0] = new Car();
garage[1] = new ElectricCar();
garage[2] = new ElectricCar();
garage[3] = new Car();
for(int i=0; i<garage.length; i++){
garage[i].turnOn();
}
Null pointer error
List<Car> garage = new ArrayList<Car>(20);
garage.set( 0, new Car() );
garage.set( 1, new ElectricCar() );
garage.set( 2, new ElectricCar() );
garage.set( 3, new Car());
for(int i; i<garage.size(); i++){
Car c = garage.get(i);
c.turnOn();
}
22
Example III
List l = new ArrayList(2); // 2 refs to null
l.add(new Integer(11)); // 11 in position 0
l.add(0, new Integer(13)); // 11 in position 1
l.set(0, new Integer(20)); // 13 replaced by 20
l.add(9, new Integer(30)); // NO: out of
bounds
l.add(new Integer(30)); // OK, size
extended
23
Queue
 Collection whose elements have an
order (
 not and ordered collection though
 Defines a head position where is the
first element that can be accessed
 peek()
 poll()
24
Queue implementations
 LinkedList
 head is the first element of the list
 FIFO: Fist-In-First-Out
 PriorityQueue
 head is the smallest element
25
Queue example
Queue<Integer> fifo =
new LinkedList<Integer>();
Queue<Integer> pq =
new PriorityQueue<Integer>();
fifo.add(3); pq.add(3);
fifo.add(1); pq.add(1);
fifo.add(2); pq.add(2);
System.out.println(fifo.peek()); // 3
System.out.println(pq.peek()); // 1
26
Set
 Contains no methods other than those
inherited from Collection
 add()has restriction that no duplicate
elements are allowed
 e1.equals(e2) == false e1,e2
 Iterator
 The elements are traversed in no
particular order
The equals() Contract
• It is reflexive: x.equals(x) == true
• It is symmetric: x.equals(y) == y.equals(x)
• It is transitive: for any reference values x, y, and z,
if x.equals(y) == true AND y.equals(z) == true
=> x.equals(z) == true
• It is consistent: for any reference values x and y,
multiple invocations of x.equals(y) consistently return
true (or false), provided that no information used in
equals comparisons on the object is modified.
• x.equals(null) == false
hashCode
The hashCode() contract
• The hashCode() method must consistently
return the same int, if no information used in
equals() comparisons on the object is modified.
• If two objects are equal for equals() method,
then calling the hashCode() method on the two
objects must produce the same integer result.
• If two objects are unequal for equals() method,
then calling the hashCode() method on the two
objects MAY produce distinct integer results.
• producing distinct int results for unequal objects
may improve the performance of hashtables
HashCode()
equals() and hashcode()
 equals() and hashCode() are bound together by
a joint contract that specifies if two objects are
considered equal using the equals() method,
then they must have identical hashcode values.
To be truly safe:
 If override equals(), override hashCode()
 Objects that are equals have to return identical
hashcodes.
32
SortedSet
 No duplicate elements
 Iterator
 The elements are traversed according to the
natural ordering (ascending)
 Augments Set interface
 Object first()
 Object last()
 SortedSet headSet(Object toElement)
 SortedSet tailSet(Object fromElement)
 SortedSet subSet(Object from, Object to)
33
Set implementations
 HashSet implements Set
 Hash tables as internal data structure
(faster)
 LinkedHashSet extends HashSet
 Elements are traversed by iterator
according to the insertion order
 TreeSet implements SortedSet
 R-B trees as internal data structure
(computationally expensive)
34
Note on sorted collections
 Depending on the constructor used
they require different implementation
of the custom ordering
 TreeSet()
 Natural ordering (elements must be
implementations of Comparable)
 TreeSet(Comparator c)
 Ordering is according to the comparator
rules, instead of natural ordering
Associative containers
(Maps)
Map<K,V>
SortedMap<K,V>
36
SortedMap
 The elements are traversed according
to the keys’ natural ordering
(ascending)
 Augments Map interface
 SortedMap subMap(K fromKey, K toKey)
 SortedMap headMap(K toKey)
 SortedMap tailMap(K fromKey)
 K firstKey()
 K lastKey()
37
Map implementations
 Analogous of Set
 HashMap implements Map
 No order
 LinkedHashMap extends HashMap
 Insertion order
 TreeMap implements SortedMap
 Ascending key order
38
HashMap
 Get/set takes constant time (in case of
no collisions)
 Automatic re-allocation when load
factor reached
 Constructor optional arguments
 load factor (default = .75)
 initial capacity (default = 16)
39
Using HashMap
Map<String,Student> students =
new HashMap<String,Student>();
students.put(“123”,
new Student(“123”,“Joe Smith”));
Student s = students.get(“123”);
for(Student si: students.values()){
}
Iterators
41
Iterators and iteration
 A common operation with collections
is to iterate over their elements
 Interface Iterator provides a
transparent means to cycle through all
elements of a Collection
 Keeps track of last visited element of
the related collection
 Each time the current element is
queried, it moves on automatically
42
Iterator interface
 boolean hasNext()
 Object next()
 void remove()
43
Iterator examples
Collection<Person> persons =
new LinkedList<Person>();
…
for(Iterator<Person> i = persons.iterator();
i.hasNext(); ) {
Person p = i.next();
…
System.out.println(p);
}
Print all objects in a list
44
Iterator examples
Collection<Person> persons =
new LinkedList<Person>();
…
for(Person p: persons) {
…
System.out.println(p);
}
The for-each syntax avoids
using iterator directly
45
Iteration examples
Map<String,Person> people =
new HashMap<String,Person>();
…
Collection<Person> values = people.values();
for(Person p: values) {
System.out.println(p);
}
Print all values in a map
(variant using while)
46
Iteration examples
Map<String,Person> people =
new HashMap<String,Person>();
…
Collection<String> keys = people.keySet();
for(String ssn: keys) {
Person p = people.get(ssn);
System.out.println(ssn + " - " + p);
}
Print all keys AND values in a map
47
Iterator examples (until Java 1.4)
Collection persons = new LinkedList();
…
for(Iterator i= persons.iterator(); i.hasNext(); ) {
Person p = (Person)i.next();
…
}
Print all objects in a list
48
Iteration examples (until Java 1.4)
Map people = new HashMap();
…
Collection values = people.values();
Iterator i = values.iterator();
while( i.hasNext() ) {
Person p = (Person)i.next();
…
}
Print all values in a map
(variant using while)
49
Iteration examples (until Java 1.4)
Map people = new HashMap();
…
Collection keys = people.keySet();
for(Iterator i= keys.iterator(); i.hasNext();) {
String ssn = (String)i.next();
Person p = (Person)people.get(ssn);
…
}
Print all keys AND values in a map
50
Note well
 It is unsafe to iterate over a collection
you are modifying (add/del) at the
same time
 Unless you are using the iterator
methods
 Iterator.remove()
 ListIterator.add()
51
Delete
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (Iterator<?> itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==1)
lst.remove(count); // wrong
count++;
}
ConcurrentModificationException
52
Delete (cont’d)
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (Iterator<?> itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==1)
itr.remove(); // ok
count++;
} Correct
53
Add
List lst = new LinkedList();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (Iterator itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==2)
lst.add(count, new Integer(22));//wrong
count++;
}
ConcurrentModificationException
54
Add (cont’d)
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (ListIterator<Integer> itr =
lst.listIterator(); itr.hasNext();){
itr.next();
if (count==2)
itr.add(new Integer(22)); // ok
count++;
}
Correct
Objects Ordering
56
Comparable interface
 Compares the receiving object with the
specified object.
 Return value must be:
 <0 if this precedes obj
 ==0 if this has the same order as obj
 >0 if this follows obj
public interface Comparable<T> {
public int compareTo(T obj);
}
57
Comparable
 The interface is implemented by language
common types in packages java.lang and
java.util
 String objects are lexicographically
ordered
 Date objects are chronologically ordered
 Number and sub-classes are ordered
numerically
58
Custom ordering
 How to define an ordering upon
Student objects according to the
“natural alphabetic order”
public class Student
implements Comparable<Student>{
private String first;
private String last;
public int compareTo(Student o){
...
}
}
59
Custom ordering
public int compareTo(Student o){
int cmp = lastName.compareTo(s.lastName);
if(cmp!=0)
return cmp;
else
return firstName.compareTo(s.firstName);
}
60
Ordering “the old way”
 In pre Java 5 code we had:
 public int compareTo(Object obj)
 No control on types
 A cast had to be performed within the
method
 Possible ClassCastException when
comparing objects of unrelated types
61
Ordering “the old way”
public int compareTo(Object obj){
Student s = (Student)obj;
int cmp = lastName.compareTo(s.lastName);
if(cmp!=0)
return cmp;
else
return firstName.compareTo(s.firstName);
}
possible
run-time error
62
Custom ordering (alternative)
 java.util
 Compares its two arguments
 Return value must be
 <0 if o1 precedes o2
 ==0 if o1 has the same ordering as o2
 >0 if o1 follows o2
public interface Comparator<T> {
public int compare(T o1, T o2);
}
63
Custom ordering (alternative)
class StudentIDComparator
implements Comparator<Student> {
public int compare(Student s1, Student s2){
return s1.getID() - s2.getID();
}
}
 Usually used to define alternative orderings
to Comparable
 The “old way” version compares two Object
references
Algorithms
65
Algorithms
 Static methods of java.util.Collections class
 Work on lists
 sort() - merge sort, n log(n)
 binarySearch() – requires ordered sequence
 shuffle() – unsort
 reverse() - requires ordered sequence
 rotate() – of given a distance
 min(), max() – in a Collection
66
Sort method
 Two generic overloads:
 on Comparable objects:
public static <T extends Comparable<? super T>>
void sort(List<T> list)
 using a Comparator object:
public static <T>
void sort(List<T> list, Comparator<? super T>)
67
Sort generic
 Why <? super T> instead of just <T> ?
 Suppose you define
– MasterStudent extends Student { }
 Intending to inherit the Student ordering
– It does not implement
Comparable<MasterStudent>
– But MasterStudent extends (indirectly)
Comparable<Student>
T extends Comparable<? super T>
Student MasterStudentMasterStudent
68
Custom ordering (alternative)
List students = new LinkedList();
students.add(new Student(“Mary”,“Smith”,34621));
students.add(new Student(“Alice”,“Knight”,13985));
students.add(new Student(“Joe”,“Smith”,95635));
Collections.sort(students); // sort by name
Collections.sort(students,
new StudentIDComparator()); // sort by ID
69
Search
 <T> int binarySearch(List<? extends
Comparable<? super T>> l, T key)
 Searches the specified object
 List must be sorted into ascending order
according to natural ordering
 <T> int binarySearch(List<? extends T> l,
T key, Comparator<? super T> c)
 Searches the specified object
 List must be sorted into ascending order
according to the specified comparator
70
Algorithms - Arrays
 Static methods of java.util.Arrays class
 Work on object arrays
 sort()
 binarySearch()
71
Search - Arrays
 int binarySearch(Object[] a, Object key)
 Searches the specified object
 Array must be sorted into ascending
order according to natural ordering
 int binarySearch(Object[] a, Object key,
Comparator c)
 Searches the specified object
 Array must be sorted into ascending
order according to the specified
comparator

Weitere ähnliche Inhalte

Was ist angesagt?

Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 

Was ist angesagt? (20)

Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Java collections
Java collectionsJava collections
Java collections
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Generics
GenericsGenerics
Generics
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
L11 array list
L11 array listL11 array list
L11 array list
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 

Andere mochten auch

Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialMarcus Biel
 
Introduction to the Algorithm Game
Introduction to the Algorithm GameIntroduction to the Algorithm Game
Introduction to the Algorithm GameIvan Orozco
 
Adroit learn java in 21 days
Adroit   learn java in 21 daysAdroit   learn java in 21 days
Adroit learn java in 21 daysadroitinfogen
 
Javadoc study and presentation
Javadoc study and presentationJavadoc study and presentation
Javadoc study and presentationFu-Lung Chen
 
DITA getting started
DITA getting startedDITA getting started
DITA getting startedRaghu nath
 
API workshop: Deep dive into Java
API workshop: Deep dive into JavaAPI workshop: Deep dive into Java
API workshop: Deep dive into JavaTom Johnson
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data TypesTareq Hasan
 
Ajax 101 Workshop
Ajax 101 WorkshopAjax 101 Workshop
Ajax 101 WorkshopBill Scott
 
Presentación Java Evolution - GlobalLogic Club
Presentación Java Evolution - GlobalLogic ClubPresentación Java Evolution - GlobalLogic Club
Presentación Java Evolution - GlobalLogic ClubGlobalLogic Latinoamérica
 
OMD chapter 2 Class modelling
 OMD  chapter 2 Class modelling OMD  chapter 2 Class modelling
OMD chapter 2 Class modellingjayashri kolekar
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with ZippersAlex Miller
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream ProcessingAlex Miller
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009Alex Miller
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The CloudAlex Miller
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebAlex Miller
 

Andere mochten auch (19)

Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
 
Introduction to the Algorithm Game
Introduction to the Algorithm GameIntroduction to the Algorithm Game
Introduction to the Algorithm Game
 
Adroit learn java in 21 days
Adroit   learn java in 21 daysAdroit   learn java in 21 days
Adroit learn java in 21 days
 
Javadoc study and presentation
Javadoc study and presentationJavadoc study and presentation
Javadoc study and presentation
 
DITA getting started
DITA getting startedDITA getting started
DITA getting started
 
Javadoc guidelines
Javadoc guidelinesJavadoc guidelines
Javadoc guidelines
 
API workshop: Deep dive into Java
API workshop: Deep dive into JavaAPI workshop: Deep dive into Java
API workshop: Deep dive into Java
 
Java Docs
Java DocsJava Docs
Java Docs
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
Ajax 101 Workshop
Ajax 101 WorkshopAjax 101 Workshop
Ajax 101 Workshop
 
Presentación Java Evolution - GlobalLogic Club
Presentación Java Evolution - GlobalLogic ClubPresentación Java Evolution - GlobalLogic Club
Presentación Java Evolution - GlobalLogic Club
 
OMD chapter 2 Class modelling
 OMD  chapter 2 Class modelling OMD  chapter 2 Class modelling
OMD chapter 2 Class modelling
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream Processing
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
 
Curso Java Avanzado 3 Js Ps
Curso Java Avanzado   3 Js PsCurso Java Avanzado   3 Js Ps
Curso Java Avanzado 3 Js Ps
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic Web
 

Ähnlich wie 07 java collection

Ähnlich wie 07 java collection (20)

collections
collectionscollections
collections
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Presentation1
Presentation1Presentation1
Presentation1
 
16 containers
16   containers16   containers
16 containers
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
lec4.ppt
lec4.pptlec4.ppt
lec4.ppt
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Collections
CollectionsCollections
Collections
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
 
Lec3
Lec3Lec3
Lec3
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
DSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdfDSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdf
 
Lecture2
Lecture2Lecture2
Lecture2
 

Mehr von Abhishek Khune (16)

Clanguage
ClanguageClanguage
Clanguage
 
Java Notes
Java NotesJava Notes
Java Notes
 
Threads
ThreadsThreads
Threads
 
Sorting
SortingSorting
Sorting
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Week0 introduction
Week0 introductionWeek0 introduction
Week0 introduction
 
Binary trees
Binary treesBinary trees
Binary trees
 
Applets
AppletsApplets
Applets
 
Clanguage
ClanguageClanguage
Clanguage
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java unit2
Java unit2Java unit2
Java unit2
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Shared memory
Shared memoryShared memory
Shared memory
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 

Kürzlich hochgeladen

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 

Kürzlich hochgeladen (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 

07 java collection

  • 2. 2 Framework  Interfaces (ADT, Abstract Data Types)  Implementations (of ADT)  Algorithms (sort)  java.util.*  Java 5 released!  Lots of changes about collections
  • 6. 6 Collection  Group of elements (references to objects)  It is not specified whether they are  Ordered / not ordered  Duplicated / not duplicated  Following constructors are common to all classes implementing Collection  T()  T(Collection c)
  • 7. 7 Collection interface  int size()  boolean isEmpty()  boolean contains(Object element)  boolean containsAll(Collection c)  boolean add(Object element)  boolean addAll(Collection c)  boolean remove(Object element)  boolean removeAll(Collection c)  void clear()  Object[] toArray()  Iterator iterator()
  • 8. 8 Collection example Collection<Person> persons = new LinkedList<Person>(); persons.add( new Person(“Alice”) ); System.out.println( persons.size() ); Collection<Person> copy = new TreeSet<Person>(); copy.addAll(persons);//new TreeSet(persons) Person[] array = copy.toArray(); System.out.println( array[0] );
  • 9. 9 Map  An object that associates keys to values (e.g., SSN ⇒ Person)  Keys and values must be objects  Keys must be unique  Only one value per key  Following constructors are common to all collection implementers  T()  T(Map m)
  • 10. 10 Map interface  Object put(Object key, Object value)  Object get(Object key)  Object remove(Object key)  boolean containsKey(Object key)  boolean containsValue(Object value)  public Set keySet()  public Collection values()  int size()  boolean isEmpty()  void clear()
  • 11. 11 Map example Map<String,Person> people = new HashMap<String,Person>(); people.put( “ALCSMT”, //ssn new Person(“Alice”, “Smith”) ); people.put( “RBTGRN”, //ssn new Person(“Robert”, “Green”) ); Person bob = people.get(“RBTGRN”); if( bob == null ) System.out.println( “Not found” ); int populationSize = people.size();
  • 12. 12 Generic collections  From Java 5, all collection interfaces and classes have been redefined as Generics  Use of generics lead to code that is  safer  more compact  easier to understand  equally performing
  • 13. 13 Generic list - excerpt public interface List<E>{ void add(E x); Iterator<E> iterator(); } public interface Iterator<E>{ E next(); boolean hasNext(); }
  • 14. 14 Example Using a list of Integers  Without generics ( ArrayList list ) list.add(0, new Integer(42)); int n= ((Integer)(list.get(0))).intValue();  With generics ( ArrayList<Integer> list ) list.add(0, new Integer(42)); int n= ((Integer)(list.get(0))).intValue();  + autoboxing ( ArrayList<Integer> list ) list.add(0,new Integer(42)); int total = list.get(0).intValue();
  • 16. 16 List  Can contain duplicate elements  Insertion order is preserved  User can define insertion point  Elements can be accessed by position  Augments Collection interface
  • 17. 17 List additional methods  Object get(int index)  Object set(int index, Object element)  void add(int index, Object element)  Object remove(int index)  boolean addAll(int index, Collection c)  int indexOf(Object o)  int lastIndexOf(Object o)  List subList(int fromIndex, int toIndex)
  • 18. 18 List implementations ArrayList  get(n)  Constant time  Insert (beginning) and delete while iterating  Linear LinkedList  get(n)  Linear time  Insert (beginning) and delete while iterating  Constant
  • 19. 19 List implementations  ArrayList  ArrayList()  ArrayList(int initialCapacity)  ArrayList(Collection c)  void ensureCapacity(int minCapacity)  LinkedList  void addFirst(Object o)  void addLast(Object o)  Object getFirst()  Object getLast()  Object removeFirst()  Object removeLast()
  • 20. 20 Example I LinkedList<Integer> ll = new LinkedList<Integer>(); ll.add(new Integer(10)); ll.add(new Integer(11)); ll.addLast(new Integer(13)); ll.addFirst(new Integer(20)); //20, 10, 11, 13
  • 21. 21 Example II Car[] garage = new Car[20]; garage[0] = new Car(); garage[1] = new ElectricCar(); garage[2] = new ElectricCar(); garage[3] = new Car(); for(int i=0; i<garage.length; i++){ garage[i].turnOn(); } Null pointer error List<Car> garage = new ArrayList<Car>(20); garage.set( 0, new Car() ); garage.set( 1, new ElectricCar() ); garage.set( 2, new ElectricCar() ); garage.set( 3, new Car()); for(int i; i<garage.size(); i++){ Car c = garage.get(i); c.turnOn(); }
  • 22. 22 Example III List l = new ArrayList(2); // 2 refs to null l.add(new Integer(11)); // 11 in position 0 l.add(0, new Integer(13)); // 11 in position 1 l.set(0, new Integer(20)); // 13 replaced by 20 l.add(9, new Integer(30)); // NO: out of bounds l.add(new Integer(30)); // OK, size extended
  • 23. 23 Queue  Collection whose elements have an order (  not and ordered collection though  Defines a head position where is the first element that can be accessed  peek()  poll()
  • 24. 24 Queue implementations  LinkedList  head is the first element of the list  FIFO: Fist-In-First-Out  PriorityQueue  head is the smallest element
  • 25. 25 Queue example Queue<Integer> fifo = new LinkedList<Integer>(); Queue<Integer> pq = new PriorityQueue<Integer>(); fifo.add(3); pq.add(3); fifo.add(1); pq.add(1); fifo.add(2); pq.add(2); System.out.println(fifo.peek()); // 3 System.out.println(pq.peek()); // 1
  • 26. 26 Set  Contains no methods other than those inherited from Collection  add()has restriction that no duplicate elements are allowed  e1.equals(e2) == false e1,e2  Iterator  The elements are traversed in no particular order
  • 27. The equals() Contract • It is reflexive: x.equals(x) == true • It is symmetric: x.equals(y) == y.equals(x) • It is transitive: for any reference values x, y, and z, if x.equals(y) == true AND y.equals(z) == true => x.equals(z) == true • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true (or false), provided that no information used in equals comparisons on the object is modified. • x.equals(null) == false
  • 29. The hashCode() contract • The hashCode() method must consistently return the same int, if no information used in equals() comparisons on the object is modified. • If two objects are equal for equals() method, then calling the hashCode() method on the two objects must produce the same integer result. • If two objects are unequal for equals() method, then calling the hashCode() method on the two objects MAY produce distinct integer results. • producing distinct int results for unequal objects may improve the performance of hashtables
  • 31. equals() and hashcode()  equals() and hashCode() are bound together by a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcode values. To be truly safe:  If override equals(), override hashCode()  Objects that are equals have to return identical hashcodes.
  • 32. 32 SortedSet  No duplicate elements  Iterator  The elements are traversed according to the natural ordering (ascending)  Augments Set interface  Object first()  Object last()  SortedSet headSet(Object toElement)  SortedSet tailSet(Object fromElement)  SortedSet subSet(Object from, Object to)
  • 33. 33 Set implementations  HashSet implements Set  Hash tables as internal data structure (faster)  LinkedHashSet extends HashSet  Elements are traversed by iterator according to the insertion order  TreeSet implements SortedSet  R-B trees as internal data structure (computationally expensive)
  • 34. 34 Note on sorted collections  Depending on the constructor used they require different implementation of the custom ordering  TreeSet()  Natural ordering (elements must be implementations of Comparable)  TreeSet(Comparator c)  Ordering is according to the comparator rules, instead of natural ordering
  • 36. 36 SortedMap  The elements are traversed according to the keys’ natural ordering (ascending)  Augments Map interface  SortedMap subMap(K fromKey, K toKey)  SortedMap headMap(K toKey)  SortedMap tailMap(K fromKey)  K firstKey()  K lastKey()
  • 37. 37 Map implementations  Analogous of Set  HashMap implements Map  No order  LinkedHashMap extends HashMap  Insertion order  TreeMap implements SortedMap  Ascending key order
  • 38. 38 HashMap  Get/set takes constant time (in case of no collisions)  Automatic re-allocation when load factor reached  Constructor optional arguments  load factor (default = .75)  initial capacity (default = 16)
  • 39. 39 Using HashMap Map<String,Student> students = new HashMap<String,Student>(); students.put(“123”, new Student(“123”,“Joe Smith”)); Student s = students.get(“123”); for(Student si: students.values()){ }
  • 41. 41 Iterators and iteration  A common operation with collections is to iterate over their elements  Interface Iterator provides a transparent means to cycle through all elements of a Collection  Keeps track of last visited element of the related collection  Each time the current element is queried, it moves on automatically
  • 42. 42 Iterator interface  boolean hasNext()  Object next()  void remove()
  • 43. 43 Iterator examples Collection<Person> persons = new LinkedList<Person>(); … for(Iterator<Person> i = persons.iterator(); i.hasNext(); ) { Person p = i.next(); … System.out.println(p); } Print all objects in a list
  • 44. 44 Iterator examples Collection<Person> persons = new LinkedList<Person>(); … for(Person p: persons) { … System.out.println(p); } The for-each syntax avoids using iterator directly
  • 45. 45 Iteration examples Map<String,Person> people = new HashMap<String,Person>(); … Collection<Person> values = people.values(); for(Person p: values) { System.out.println(p); } Print all values in a map (variant using while)
  • 46. 46 Iteration examples Map<String,Person> people = new HashMap<String,Person>(); … Collection<String> keys = people.keySet(); for(String ssn: keys) { Person p = people.get(ssn); System.out.println(ssn + " - " + p); } Print all keys AND values in a map
  • 47. 47 Iterator examples (until Java 1.4) Collection persons = new LinkedList(); … for(Iterator i= persons.iterator(); i.hasNext(); ) { Person p = (Person)i.next(); … } Print all objects in a list
  • 48. 48 Iteration examples (until Java 1.4) Map people = new HashMap(); … Collection values = people.values(); Iterator i = values.iterator(); while( i.hasNext() ) { Person p = (Person)i.next(); … } Print all values in a map (variant using while)
  • 49. 49 Iteration examples (until Java 1.4) Map people = new HashMap(); … Collection keys = people.keySet(); for(Iterator i= keys.iterator(); i.hasNext();) { String ssn = (String)i.next(); Person p = (Person)people.get(ssn); … } Print all keys AND values in a map
  • 50. 50 Note well  It is unsafe to iterate over a collection you are modifying (add/del) at the same time  Unless you are using the iterator methods  Iterator.remove()  ListIterator.add()
  • 51. 51 Delete List<Integer> lst=new LinkedList<Integer>(); lst.add(new Integer(10)); lst.add(new Integer(11)); lst.add(new Integer(13)); lst.add(new Integer(20)); int count = 0; for (Iterator<?> itr = lst.iterator(); itr.hasNext(); ) { itr.next(); if (count==1) lst.remove(count); // wrong count++; } ConcurrentModificationException
  • 52. 52 Delete (cont’d) List<Integer> lst=new LinkedList<Integer>(); lst.add(new Integer(10)); lst.add(new Integer(11)); lst.add(new Integer(13)); lst.add(new Integer(20)); int count = 0; for (Iterator<?> itr = lst.iterator(); itr.hasNext(); ) { itr.next(); if (count==1) itr.remove(); // ok count++; } Correct
  • 53. 53 Add List lst = new LinkedList(); lst.add(new Integer(10)); lst.add(new Integer(11)); lst.add(new Integer(13)); lst.add(new Integer(20)); int count = 0; for (Iterator itr = lst.iterator(); itr.hasNext(); ) { itr.next(); if (count==2) lst.add(count, new Integer(22));//wrong count++; } ConcurrentModificationException
  • 54. 54 Add (cont’d) List<Integer> lst=new LinkedList<Integer>(); lst.add(new Integer(10)); lst.add(new Integer(11)); lst.add(new Integer(13)); lst.add(new Integer(20)); int count = 0; for (ListIterator<Integer> itr = lst.listIterator(); itr.hasNext();){ itr.next(); if (count==2) itr.add(new Integer(22)); // ok count++; } Correct
  • 56. 56 Comparable interface  Compares the receiving object with the specified object.  Return value must be:  <0 if this precedes obj  ==0 if this has the same order as obj  >0 if this follows obj public interface Comparable<T> { public int compareTo(T obj); }
  • 57. 57 Comparable  The interface is implemented by language common types in packages java.lang and java.util  String objects are lexicographically ordered  Date objects are chronologically ordered  Number and sub-classes are ordered numerically
  • 58. 58 Custom ordering  How to define an ordering upon Student objects according to the “natural alphabetic order” public class Student implements Comparable<Student>{ private String first; private String last; public int compareTo(Student o){ ... } }
  • 59. 59 Custom ordering public int compareTo(Student o){ int cmp = lastName.compareTo(s.lastName); if(cmp!=0) return cmp; else return firstName.compareTo(s.firstName); }
  • 60. 60 Ordering “the old way”  In pre Java 5 code we had:  public int compareTo(Object obj)  No control on types  A cast had to be performed within the method  Possible ClassCastException when comparing objects of unrelated types
  • 61. 61 Ordering “the old way” public int compareTo(Object obj){ Student s = (Student)obj; int cmp = lastName.compareTo(s.lastName); if(cmp!=0) return cmp; else return firstName.compareTo(s.firstName); } possible run-time error
  • 62. 62 Custom ordering (alternative)  java.util  Compares its two arguments  Return value must be  <0 if o1 precedes o2  ==0 if o1 has the same ordering as o2  >0 if o1 follows o2 public interface Comparator<T> { public int compare(T o1, T o2); }
  • 63. 63 Custom ordering (alternative) class StudentIDComparator implements Comparator<Student> { public int compare(Student s1, Student s2){ return s1.getID() - s2.getID(); } }  Usually used to define alternative orderings to Comparable  The “old way” version compares two Object references
  • 65. 65 Algorithms  Static methods of java.util.Collections class  Work on lists  sort() - merge sort, n log(n)  binarySearch() – requires ordered sequence  shuffle() – unsort  reverse() - requires ordered sequence  rotate() – of given a distance  min(), max() – in a Collection
  • 66. 66 Sort method  Two generic overloads:  on Comparable objects: public static <T extends Comparable<? super T>> void sort(List<T> list)  using a Comparator object: public static <T> void sort(List<T> list, Comparator<? super T>)
  • 67. 67 Sort generic  Why <? super T> instead of just <T> ?  Suppose you define – MasterStudent extends Student { }  Intending to inherit the Student ordering – It does not implement Comparable<MasterStudent> – But MasterStudent extends (indirectly) Comparable<Student> T extends Comparable<? super T> Student MasterStudentMasterStudent
  • 68. 68 Custom ordering (alternative) List students = new LinkedList(); students.add(new Student(“Mary”,“Smith”,34621)); students.add(new Student(“Alice”,“Knight”,13985)); students.add(new Student(“Joe”,“Smith”,95635)); Collections.sort(students); // sort by name Collections.sort(students, new StudentIDComparator()); // sort by ID
  • 69. 69 Search  <T> int binarySearch(List<? extends Comparable<? super T>> l, T key)  Searches the specified object  List must be sorted into ascending order according to natural ordering  <T> int binarySearch(List<? extends T> l, T key, Comparator<? super T> c)  Searches the specified object  List must be sorted into ascending order according to the specified comparator
  • 70. 70 Algorithms - Arrays  Static methods of java.util.Arrays class  Work on object arrays  sort()  binarySearch()
  • 71. 71 Search - Arrays  int binarySearch(Object[] a, Object key)  Searches the specified object  Array must be sorted into ascending order according to natural ordering  int binarySearch(Object[] a, Object key, Comparator c)  Searches the specified object  Array must be sorted into ascending order according to the specified comparator