SlideShare a Scribd company logo
description of Collections, seaching & Sorting
 The data structures that you choose can make a big difference when
it comes to implementing methods in a natural style, as well as for
performance. Do you need to search quickly through thousands of
sorted items? Do you need to rapidly insert and remove elements
in the middle of an ordered sequence? Do you need to establish
associations between keys and values?
 In object-oriented thinking, a data structure, also known as a
container, is an object that stores other objects, referred to as
data or elements. Some people refer to data structures as
container objects
 A collection is a container object that represents a group of
objects, often referred to as elements. A collection allows a group of
objects to be treated as a single unit
 As is common for modern data structure libraries, the Java
collection library separates interfaces and implementations.
2
 The Java Collections Framework supports two
types of containers:
 One for storing a collection of elements,
simply called a Collection.
 The other for storing key/value pairs, called a
Map.
 The Java Collections Framework supports
three types of collections
 Sets - An instance of Set stores a group of
non-duplicate elements.
 Lists - An instance of List stores an ordered
collection of elements.
 Queue - An instance of Queue stores objects
that are processed in first-in, first-out fashion
3
 The collections framework is provided in
java.util package and has three main elements
 core interfaces, which allow collections to be
manipulated independent of their implementation
 small set of implementation classes, providing data
structures for you to use
 an assortment of algorithms, which can be used to
perform various operations on collections, such as
sorting and searching
4
 add(Object o), addAll(Collection c)
 ensures that this collection contains the specified element
 remove(Object o), removeAll(Collection c)
 removes a single instance of the specified element from
this collection, or all the elements
 size()
 returns the number of elements in this collection
 clear()
 removes all of the elements from this collection
 toArray()
 returns an array containing all of the elements in this
collection
 iterator()
 returns an iterator over the elements in this collection
5
 Collection
 basic interface that defines all collection operations
 Set
 extends the Collection interface for sets that maintain
unique elements
 List
 extends the Collection interface for group of elements in a
sequential order
 Map
 basic interface for a group of key to value mappings
 Additional Interfaces
 SortedSet
 for sets with elements in sorted order
 SortedMap
 for maps with keys in sorted order 6
Collection Type Description
ArrayList An indexed sequence that grows and shrinks dynamically
LinkedList An ordered sequence that allows efficient insertions and
removal at any location
ArrayDeque A double-ended queue that is implemented as a circular array
HashSet An unordered collection that rejects duplicates
TreeSet A sorted set
EnumSet A set of enumerated type values
LinkedHashSet A set that remembers the order in which elements were
inserted
PriorityQueue A collection that allows efficient removal of the smallest
element
HashMap data structure that stores key/value associations
TreeMap A map in which the keys are sorted
EnumMap A map in which the keys belong to an enumerated type 7
 implementations will maintain their elements in
sequential order or sequence
 can contain duplicates
 List interface adds list specific operations
 access by numerical position
 search in list
 operations on parts of a list (called open range-view
operations)
 customized iterators
8
 resizable-array implementation of the List interface
 implements all optional list operations, and permits
all elements, including null
 in addition to implementing the List interface, this
class provides methods to manipulate the size of the
array that is used internally to store the list
 capacity is the size of the array used to store the
elements in the list
 as elements are added to ArrayList, its capacity grows
automatically
 ensureCapacity() increases the capacity of an
ArrayList instance before adding a large number of
elements
 reduces the amount of incremental reallocation
9
 see ArrayListExample1.java
10
The size is: 6
This
is
is
a
a
test
 see ArrayListExample2.java
11
The size is: 6
This
is
is
a
a
test
 Vector is similar to ArrayList, but is thread
safe / synchronized
12
element
List
element
…
Thread
1
Thread
2
 can add elements at end and beginning to a
LinkedList
 The Example...
 List where each element references previous and
next element in the list
13
 see ListExample.java
 list where each element references previous
and next element in the list
14
Results:
The size is: 6
This
is
is
a
a
test
COMPARE WITH:
list.add("is");
list.add("is");
list.add("a");
list.add("a");
list.addLast("test");
list.addFirst("This");
 If you need to support random access through an
index without inserting or removing elements from
any place other than the end, ArrayList offers the
most efficient collection.
 If, however, your application requires the insertion
or deletion of elements from any place in the list,
you should choose LinkedList.
 A list can grow or shrink dynamically. An array is
fixed once it is created. If your application does not
require insertion or deletion of elements, the most
efficient data structure is the array.
15
 The Stack class represents a last-in first-out stack of objects
 The elements are accessed only from the top of the stack
 You can retrieve, insert, or remove an element from the top of the
stack
 boolean empty() Tests if this stack is empty.
 Object peek() Looks at the object at the top of this stack
without removing it from the stack.
 Object pop() Removes the object at the top of this stack and
returns that object as the value of this function.
 Object push(Object item) Pushes an item onto the top of this
stack.
 int search(Object o) Returns the 1-based position where an
object is on this stack.
16
 interface Map maps keys to values
 no duplicate keys
 each key maps to only one value
 value is retrieved based on a key
 the keys order can be sorted (TreeMap), or not
 methods:
 put(Object key, Object value)
 get(Object key)
 remove(Object key)
 containsKey(Object key)
 containsValue(Object value) caution - could be
expensive!
17
 see HashMapExample.java
18
Results:
The size is: 6
five=cinco
six=seis
two=dos
one=uno
three=tres
four=cuatro
COMPARE WITH:
map.put("one","uno");
map.put("two","deux");
map.put("two","dos");
map.put("three","tres");
map.put("four","cuatro");
map.put("five","cinco");
map.put("six","seis");
 Hashtable is synchronized, whereas HashMap is
not. This makes HashMap better for non-threaded
applications, as unsynchronized Objects typically
perform better than synchronized ones.
 Hashtable does not allow null keys or values.
HashMap allows one null key and any number of
null values.
 One of HashMap's subclasses is LinkedHashMap,
so in the event that you'd want predictable iteration
order (which is insertion order by default), you could
easily swap out the HashMap for a LinkedHashMap.
This wouldn't be as easy if you were using
Hashtable. 19
 java.util.Hashtable
 stores data items based on a key derived from
a given formula
 unique key returned by hashCode()
 use Hashtable class if you will be storing a
large amount of data in memory and then
searching it
20
 see HashtableExample.java
 we stored name value pairs, where:
 name = animals
 value = color
 Java computed it’s own hash number
 we retrieved data by entering name ("cow" in
our case)
21
{Dog=white, Fly=black, Hen=red, Ant=black, Cow=orange, Pig=pink,
Cat=blue}
Which animal? Cow
Cow : orange
 The Collections class contains various static
methods for operating on collections and
maps, for creating synchronized collection
classes, and for creating read-only collection
classes.
22
TestCollections
 The Arrays class contains various static
methods for sorting and searching arrays, for
comparing arrays, and for filling array elements.
 It also contains a method for converting an
array to a list.
23
TestArrays
ArrayList<String> items = new
ArrayList<String>();
items.add("Orange");
items.add("Green");
items.add("White");
String[] colours = items.toArray(new String[0]);
CollectionUtil.display(colours);

24
 Iterator provides a way to access the elements of
the collection sequentially without exposing its
underlying representation
 boolean hasNext()
 returns true if the iteration has more elements
 Object next()
 returns the next element in the iteration
 void remove()
 removes from the underlying collection the last element
returned by the iterator (optional operation)
25
 implementations of Set will not allow duplicate
elements
 it does not add any new methods to Collection
interface,
 but adds the restriction that duplicates are not
allowed
 a Set models a mathematical set
26
 Results:
 The size is: 4
 a
 is
 This
 test
27
HashSetExample
 The HashSet class is a concrete class that implements the
Set interface
 It can be used to store duplicate-free elements
 uses hashcode() to determine if an object has been added to the
set “SEE NEXT SLIDES ABOUT HASH CODE”
28
 Implementing hashcode: if a class overrides equals, it must
override hashCode when they are both overridden, equals
and hashCode must use the same set of fields
 if two objects are equal, then their hashCode values must be
equal as well. It is a popular misconception that hashCode
provides a unique identifier for an object. It does not.
 hashCode() methodwhich digests the data stored in an instance of
the class into a single hash value (a 32-bit signed integer). This hash
is used by other code when storing or manipulating the instance - the
values are intended to be evenly distributed for varied inputs in order
to avoid clustering. This property is important to the performance of
hashtables and other data structures that store objects in groups
("buckets") based on their computed hash values
 The semantics of equals() for a given class are left to the
implementer; defining what equals() means for a given class is part
of the design work for that class. The default implementation,
provided by Object, is simply reference equality: Under this default
implementation, two references are equal only if they refer to the
exact same object.
 The default implementation of hashCode() provided by Object is
derived by mapping the memory address of the object to an integer
value. Because on some architectures the address space is larger
than the range of values for int, it is possible that two distinct
objects could have the same hashCode(). If you override
hashCode(), you can still use the System.identityHashCode()
method to access this default value.
 What would happen if Integer did not override equals() and
hashCode()? Nothing, if we never used an Integer as a key in a
HashMap or other hash-based collection. However, if we were to use
such an Integer object for a key in a HashMap, we would not be able to
reliably retrieve the associated value, unless we used the exact same
Integer instance in the get() call as we did in the put() call. This would
require ensuring that we only use a single instance of the Integer
object corresponding to a particular integer value throughout our
program. Needless to say, this approach would be inconvenient and
error prone.
29
 Why does our root object class need hashCode(), when its discriminating
ability is entirely subsumed by that of equals()? The hashCode() method
exists purely for efficiency. The Java platform architects anticipated the
importance of hash-based collection classes -- such as Hashtable,
HashMap, and HashSet -- in typical Java applications, and comparing
against many objects with equals() can be computationally expensive.
Having every Java object support hashCode() allows for efficient storage
and retrieval using hash-based collections
 The behavior of equals() and hashCode() may even be imposed by the
specification of a superclass or interface. For example, the List interface
requires that a List object is equal to another object if and only if the other
object is also a List and they contain the same elements (Object.equals()
on the elements) in the same order. The requirements for hashCode() are
defined -- the hashCode() value of a list must conform to the following
calculation:

30
hashCode = 1; Iterator i = list.iterator();
while (i.hasNext()) { Object obj = i.next();
hashCode = 31*hashCode + (o
Not only is the hash value dependent on the contents of the list, but the specific
algorithm for combining the hash values of the individual elements is specified as
well.bj==null ? 0 : obj.hashCode()); }
 Previously, we used Comparator with Arrays, now
lets try it out with collections
 Comparators can be used to control the order of
certain data structures (such as TreeSet or
TreeMap).
31
The Comparator interface declares a compare method with two explicit
parameters:
public interface Comparator<T>
{
int compare(T a, T b);
}
Just like the compareTo method, the compare method returns a negative
integer if a comes before b, zero if they are identical, or a positive integer
otherwise
 see CompareSortExample.java
32
Leopard
Deer
Cow
Cat
Cougar
Lion
Dog
--------------------------
Cow
Cat
Dog
Deer
Lion
Cougar
Leopard
Notice that sorting is based on word length;
not alphabetic order
 When you take an element out of a Collection,
you must cast it to the type of element that is
stored in the collection.
 Besides being inconvenient, this is unsafe.
 The compiler does not check that your cast is the
same as the collection's type, so the cast can fail at
run time.
33
 Generics provides a way for you to
communicate the type of a collection to the
compiler, so that it can be checked.
 Once the compiler knows the element type of
the collection, the compiler can check that you
have used the collection consistently and can
insert the correct casts on values being taken
out of the collection.
34
 Here is a simple example taken from the
existing Collections tutorial:
// Removes 4-letter words from c. Elements
must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}
35
ex·pur·gate· (eks′pər gāt′)
transitive verb
to remove passages considered obscene or otherwise objectionable from (a book,
etc.) to expunge (objectionable material) from; delete
 Here is the same example modified to use
generics:
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator();
i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
36
37
Results:
The size is: 4
a
is
This
test
HashSetExample2
 http://java.sun.com/docs/books/tutorial/
collections/index.html
 Java Collections Framework
38

More Related Content

Similar to description of Collections, seaching & Sorting (20)

PPTX
Javasession7
Rajeev Kumar
 
PDF
07 java collection
Abhishek Khune
 
PPTX
Java Hands-On Workshop
Arpit Poladia
 
PPT
Java collection
Arati Gadgil
 
PDF
javacollections.pdf
ManojKandhasamy1
 
PPTX
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
PPT
java collections
javeed_mhd
 
PPT
JavaCollections.ppt
Irfanhabeeb18
 
PPT
JavaCollections.ppt
boopathirajaraja1
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
DOC
Advanced core java
Rajeev Uppala
 
PPT
Best core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
PPT
Collections Framework
Sunil OS
 
PPTX
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
PDF
Collections and generics
Muthukumaran Subramanian
 
PPTX
Pptchdtdtfygugyxthgihhihigugufydtdfzrzrzrtdyfyfy
dnthulk
 
PPT
sets and maps
Rajkattamuri
 
PPTX
22.collections(1)
Sirisha Chillakanti
 
Javasession7
Rajeev Kumar
 
07 java collection
Abhishek Khune
 
Java Hands-On Workshop
Arpit Poladia
 
Java collection
Arati Gadgil
 
javacollections.pdf
ManojKandhasamy1
 
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
java collections
javeed_mhd
 
JavaCollections.ppt
Irfanhabeeb18
 
JavaCollections.ppt
boopathirajaraja1
 
Collections in Java Notes
Shalabh Chaudhary
 
Advanced core java
Rajeev Uppala
 
Best core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
Collections Framework
Sunil OS
 
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
Collections and generics
Muthukumaran Subramanian
 
Pptchdtdtfygugyxthgihhihigugufydtdfzrzrzrtdyfyfy
dnthulk
 
sets and maps
Rajkattamuri
 
22.collections(1)
Sirisha Chillakanti
 

More from mdimberu (6)

PDF
Structure-Decorator deign pattern model fact
mdimberu
 
PDF
Structure-Composite Structure deign pattern model fact
mdimberu
 
PDF
Structure Facade deign pattern model fact
mdimberu
 
PDF
Behave State deign pattern test model fact
mdimberu
 
PDF
design pattern Behavior Visitor model aspect
mdimberu
 
PDF
software Structural design pattern Adapter
mdimberu
 
Structure-Decorator deign pattern model fact
mdimberu
 
Structure-Composite Structure deign pattern model fact
mdimberu
 
Structure Facade deign pattern model fact
mdimberu
 
Behave State deign pattern test model fact
mdimberu
 
design pattern Behavior Visitor model aspect
mdimberu
 
software Structural design pattern Adapter
mdimberu
 
Ad

Recently uploaded (20)

PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Simplify React app login with asgardeo-sdk
vaibhav289687
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PDF
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
PDF
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PPTX
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
PPTX
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Simplify React app login with asgardeo-sdk
vaibhav289687
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Ad

description of Collections, seaching & Sorting

  • 2.  The data structures that you choose can make a big difference when it comes to implementing methods in a natural style, as well as for performance. Do you need to search quickly through thousands of sorted items? Do you need to rapidly insert and remove elements in the middle of an ordered sequence? Do you need to establish associations between keys and values?  In object-oriented thinking, a data structure, also known as a container, is an object that stores other objects, referred to as data or elements. Some people refer to data structures as container objects  A collection is a container object that represents a group of objects, often referred to as elements. A collection allows a group of objects to be treated as a single unit  As is common for modern data structure libraries, the Java collection library separates interfaces and implementations. 2
  • 3.  The Java Collections Framework supports two types of containers:  One for storing a collection of elements, simply called a Collection.  The other for storing key/value pairs, called a Map.  The Java Collections Framework supports three types of collections  Sets - An instance of Set stores a group of non-duplicate elements.  Lists - An instance of List stores an ordered collection of elements.  Queue - An instance of Queue stores objects that are processed in first-in, first-out fashion 3
  • 4.  The collections framework is provided in java.util package and has three main elements  core interfaces, which allow collections to be manipulated independent of their implementation  small set of implementation classes, providing data structures for you to use  an assortment of algorithms, which can be used to perform various operations on collections, such as sorting and searching 4
  • 5.  add(Object o), addAll(Collection c)  ensures that this collection contains the specified element  remove(Object o), removeAll(Collection c)  removes a single instance of the specified element from this collection, or all the elements  size()  returns the number of elements in this collection  clear()  removes all of the elements from this collection  toArray()  returns an array containing all of the elements in this collection  iterator()  returns an iterator over the elements in this collection 5
  • 6.  Collection  basic interface that defines all collection operations  Set  extends the Collection interface for sets that maintain unique elements  List  extends the Collection interface for group of elements in a sequential order  Map  basic interface for a group of key to value mappings  Additional Interfaces  SortedSet  for sets with elements in sorted order  SortedMap  for maps with keys in sorted order 6
  • 7. Collection Type Description ArrayList An indexed sequence that grows and shrinks dynamically LinkedList An ordered sequence that allows efficient insertions and removal at any location ArrayDeque A double-ended queue that is implemented as a circular array HashSet An unordered collection that rejects duplicates TreeSet A sorted set EnumSet A set of enumerated type values LinkedHashSet A set that remembers the order in which elements were inserted PriorityQueue A collection that allows efficient removal of the smallest element HashMap data structure that stores key/value associations TreeMap A map in which the keys are sorted EnumMap A map in which the keys belong to an enumerated type 7
  • 8.  implementations will maintain their elements in sequential order or sequence  can contain duplicates  List interface adds list specific operations  access by numerical position  search in list  operations on parts of a list (called open range-view operations)  customized iterators 8
  • 9.  resizable-array implementation of the List interface  implements all optional list operations, and permits all elements, including null  in addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list  capacity is the size of the array used to store the elements in the list  as elements are added to ArrayList, its capacity grows automatically  ensureCapacity() increases the capacity of an ArrayList instance before adding a large number of elements  reduces the amount of incremental reallocation 9
  • 10.  see ArrayListExample1.java 10 The size is: 6 This is is a a test
  • 11.  see ArrayListExample2.java 11 The size is: 6 This is is a a test
  • 12.  Vector is similar to ArrayList, but is thread safe / synchronized 12 element List element … Thread 1 Thread 2
  • 13.  can add elements at end and beginning to a LinkedList  The Example...  List where each element references previous and next element in the list 13
  • 14.  see ListExample.java  list where each element references previous and next element in the list 14 Results: The size is: 6 This is is a a test COMPARE WITH: list.add("is"); list.add("is"); list.add("a"); list.add("a"); list.addLast("test"); list.addFirst("This");
  • 15.  If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection.  If, however, your application requires the insertion or deletion of elements from any place in the list, you should choose LinkedList.  A list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array. 15
  • 16.  The Stack class represents a last-in first-out stack of objects  The elements are accessed only from the top of the stack  You can retrieve, insert, or remove an element from the top of the stack  boolean empty() Tests if this stack is empty.  Object peek() Looks at the object at the top of this stack without removing it from the stack.  Object pop() Removes the object at the top of this stack and returns that object as the value of this function.  Object push(Object item) Pushes an item onto the top of this stack.  int search(Object o) Returns the 1-based position where an object is on this stack. 16
  • 17.  interface Map maps keys to values  no duplicate keys  each key maps to only one value  value is retrieved based on a key  the keys order can be sorted (TreeMap), or not  methods:  put(Object key, Object value)  get(Object key)  remove(Object key)  containsKey(Object key)  containsValue(Object value) caution - could be expensive! 17
  • 18.  see HashMapExample.java 18 Results: The size is: 6 five=cinco six=seis two=dos one=uno three=tres four=cuatro COMPARE WITH: map.put("one","uno"); map.put("two","deux"); map.put("two","dos"); map.put("three","tres"); map.put("four","cuatro"); map.put("five","cinco"); map.put("six","seis");
  • 19.  Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.  Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.  One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. 19
  • 20.  java.util.Hashtable  stores data items based on a key derived from a given formula  unique key returned by hashCode()  use Hashtable class if you will be storing a large amount of data in memory and then searching it 20
  • 21.  see HashtableExample.java  we stored name value pairs, where:  name = animals  value = color  Java computed it’s own hash number  we retrieved data by entering name ("cow" in our case) 21 {Dog=white, Fly=black, Hen=red, Ant=black, Cow=orange, Pig=pink, Cat=blue} Which animal? Cow Cow : orange
  • 22.  The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read-only collection classes. 22 TestCollections
  • 23.  The Arrays class contains various static methods for sorting and searching arrays, for comparing arrays, and for filling array elements.  It also contains a method for converting an array to a list. 23 TestArrays
  • 24. ArrayList<String> items = new ArrayList<String>(); items.add("Orange"); items.add("Green"); items.add("White"); String[] colours = items.toArray(new String[0]); CollectionUtil.display(colours);  24
  • 25.  Iterator provides a way to access the elements of the collection sequentially without exposing its underlying representation  boolean hasNext()  returns true if the iteration has more elements  Object next()  returns the next element in the iteration  void remove()  removes from the underlying collection the last element returned by the iterator (optional operation) 25
  • 26.  implementations of Set will not allow duplicate elements  it does not add any new methods to Collection interface,  but adds the restriction that duplicates are not allowed  a Set models a mathematical set 26
  • 27.  Results:  The size is: 4  a  is  This  test 27 HashSetExample  The HashSet class is a concrete class that implements the Set interface  It can be used to store duplicate-free elements  uses hashcode() to determine if an object has been added to the set “SEE NEXT SLIDES ABOUT HASH CODE”
  • 28. 28  Implementing hashcode: if a class overrides equals, it must override hashCode when they are both overridden, equals and hashCode must use the same set of fields  if two objects are equal, then their hashCode values must be equal as well. It is a popular misconception that hashCode provides a unique identifier for an object. It does not.  hashCode() methodwhich digests the data stored in an instance of the class into a single hash value (a 32-bit signed integer). This hash is used by other code when storing or manipulating the instance - the values are intended to be evenly distributed for varied inputs in order to avoid clustering. This property is important to the performance of hashtables and other data structures that store objects in groups ("buckets") based on their computed hash values
  • 29.  The semantics of equals() for a given class are left to the implementer; defining what equals() means for a given class is part of the design work for that class. The default implementation, provided by Object, is simply reference equality: Under this default implementation, two references are equal only if they refer to the exact same object.  The default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value. Because on some architectures the address space is larger than the range of values for int, it is possible that two distinct objects could have the same hashCode(). If you override hashCode(), you can still use the System.identityHashCode() method to access this default value.  What would happen if Integer did not override equals() and hashCode()? Nothing, if we never used an Integer as a key in a HashMap or other hash-based collection. However, if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same Integer instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone. 29
  • 30.  Why does our root object class need hashCode(), when its discriminating ability is entirely subsumed by that of equals()? The hashCode() method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such as Hashtable, HashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive. Having every Java object support hashCode() allows for efficient storage and retrieval using hash-based collections  The behavior of equals() and hashCode() may even be imposed by the specification of a superclass or interface. For example, the List interface requires that a List object is equal to another object if and only if the other object is also a List and they contain the same elements (Object.equals() on the elements) in the same order. The requirements for hashCode() are defined -- the hashCode() value of a list must conform to the following calculation:  30 hashCode = 1; Iterator i = list.iterator(); while (i.hasNext()) { Object obj = i.next(); hashCode = 31*hashCode + (o Not only is the hash value dependent on the contents of the list, but the specific algorithm for combining the hash values of the individual elements is specified as well.bj==null ? 0 : obj.hashCode()); }
  • 31.  Previously, we used Comparator with Arrays, now lets try it out with collections  Comparators can be used to control the order of certain data structures (such as TreeSet or TreeMap). 31 The Comparator interface declares a compare method with two explicit parameters: public interface Comparator<T> { int compare(T a, T b); } Just like the compareTo method, the compare method returns a negative integer if a comes before b, zero if they are identical, or a positive integer otherwise
  • 33.  When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection.  Besides being inconvenient, this is unsafe.  The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time. 33
  • 34.  Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked.  Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection. 34
  • 35.  Here is a simple example taken from the existing Collections tutorial: // Removes 4-letter words from c. Elements must be strings static void expurgate(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (((String) i.next()).length() == 4) i.remove(); } 35 ex·pur·gate· (eks′pər gāt′) transitive verb to remove passages considered obscene or otherwise objectionable from (a book, etc.) to expunge (objectionable material) from; delete
  • 36.  Here is the same example modified to use generics: // Removes the 4-letter words from c static void expurgate(Collection<String> c) { for (Iterator<String> i = c.iterator(); i.hasNext(); ) if (i.next().length() == 4) i.remove(); } 36
  • 37. 37 Results: The size is: 4 a is This test HashSetExample2