SlideShare a Scribd company logo
JAVA Software Development
Paradigm
Advance OO Programming
BSCS Semester 6
MCS 3
Course Instructor: Ms. Iram
java.util.Random
• Benchmarks uses the java.util.Random class
— a more controlled way to generate random
numbers.
• If we set the same seed, we get the same
“random” sequence.
Random generator1 = new Random();
Random generator2 = new Random(seed); long seed;
the seed is different
each time
int k = generator.nextInt (n);
double x = generator.nextDouble ();
0 ≤ k < n
0 ≤ x < 1
13-3
java.util.Arrays
• Provides static methods for dealing with
arrays.
• Works for arrays of numbers, Strings, and
Objects.
• Methods:
int pos = Arrays.binarySearch (arr, target);
Arrays.sort (arr);
Arrays.fill (arr, value); // fills arr with a given value
String str = Arrays.toString(arr);
Arrays.asList(arr);
Returns a representation of
arr as a fixed-length list
13-4
java.util.Collections
• Provides static methods for dealing with
ArrayLists and other Java collections.
• Works for arrays of numbers, Strings, and
Objects.
• Methods:
int pos = Collections.binarySearch (list, target);
Collections.sort (list);
Collections.shuffle (list);
19-5
Collection, Iterator
• Collection interface represents any collection.
• An iterator is an object that helps to traverse
the collection (process all its elements in
sequence).
• A collection supplies its own iterator(s),
(returned by collection’s iterator method); the
traversal sequence depends on the
collection.
«interface»
Collection
«interface»
Iterator
19-6
Collections
• Collection, Iterator
• Lists, ListIterator
 List
 ArrayList
 LinkedList
• Stack
• Queue, PriorityQueue
• Sets
 Set
 TreeSet
 HashSet
• Maps
 Map
 TreeMap
 HashMap
All these interfaces and classes are
part of the java.util package.
Names of interfaces are in italics.
19-7
Overview
«interface»
Collection
«interface»
Iterator
«interface»
Comparable
«interface»
Comparator
«interface»
Queue
«interface»
Map
Stack PriorityQueue
HashMapTreeMap
LinkedListArrayList TreeSet HashSet
«interface»
List
«interface»
Set
«interface»
ListIterator
Collection
Set
TreeSet
HashSet
List
ArrayList
LinkedList
TreeSet
TreeMap
PriorityQueue
19-8
Collection<E>
Methods
boolean isEmpty ()
int size ()
boolean contains (Object obj)
boolean add (E obj)
boolean remove (E obj)
Iterator<E> iterator ()
// ... other methods
Supplies an
iterator for this
collection
«interface»
Collection
«interface»
Iterator
19-9
Iterator<E>
Methods
boolean hasNext ()
E next ()
void remove ()
«interface»
Collection
«interface»
Iterator
What’s “next” is
determined by a
particular collection
Removes the last
visited element
19-10
Lists, ListIterator
• A list represents a collection in which all
elements are numbered by indices:
a0, a1, ..., an-1
• java.util:
 List interface
 ArrayList
 LinkedList
• ListIterator is an extended iterator, specific
for lists (ListIterator is a subinterface of
Iterator)
19-11
List<E>
Methods
«interface»
Collection
«interface»
Iterator
«interface»
ListIterator
«interface»
List
// All Collection<E> methods, plus:
E get (int i)
E set (int i, E obj)
void add (int i, E obj)
E remove (int i)
int indexOf (Object obj)
ListIterator<E> listIterator ()
ListIterator<E> listIterator (int i)
These methods
are familiar from
ArrayList, which
implements List
Returns a ListIterator
that starts iterations at
index i
19-12
ListIterator<E>
Methods
«interface»
Collection
«interface»
Iterator
«interface»
ListIterator
«interface»
List
// The three Iterator<E> methods, plus:
int nextIndex ()
boolean hasPrevious ()
E previous ()
int previousIndex ()
void add (E obj)
void set (E obj)
Can traverse the
list backward
Can add elements to the list (inserts
after the last visited element)
Can change elements (changes
the last visited element)
19-13
ArrayList
• Represents a list as a dynamic array (array
that is resized when full)
• Provides random access to the elements
• Implements all the methods of List<E>
«interface»
Iterator
«interface»
ListIterator
«interface»
List
ArrayList LinkedList
a1 a2 an-1...a0
19-14
LinkedList
• Represents a list as a doubly-linked list
with a header node
• Implements all the methods of List<E>
a0
a1 a2 an-1
...
«interface»
Iterator
«interface»
ListIterator
«interface»
List
ArrayList LinkedList
header
19-15
LinkedList
(cont’d)
• Additional methods specific to LinkedList:
«interface»
Iterator
«interface»
ListIterator
«interface»
List
ArrayList LinkedList
void addFirst (E obj)
void addLast (E obj)
E getFirst ()
E getLast ()
E removeFirst ()
E removeLast ()
19-16
ArrayList vs. LinkedList
• Implements a list as an array
+ Provides random access to
the elements
- Inserting and removing
elements requires shifting of
subsequent elements
- Needs to be resized when
runs out of space
• Implements a list as a
doubly-linked list with a
header node
- No random access to the
elements — needs to
traverse the list to get to the
i-th element
+ Inserting and removing
elements is done by
rearranging the links — no
shifting
+ Nodes are allocated and
released as necessary
12-19
java.util.ArrayList<E>
• Implements a list using an array.
• Can only hold objects (of a specified type),
not elements of primitive data types.
• Keeps track of the list capacity (the length of
the allocated array) and list size (the number
of elements currently in the list)
"Cat" "Hat" "Bat"
capacity
size
...
12-20
ArrayList  Generics
• Starting with Java 5, ArrayList and other
collection classes hold objects of a specified
data type.
• The elements’ data type is shown in angle
brackets and becomes part of the ArrayList
type. For example:
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> nums = new ArrayList<Integer>();
12-21
ArrayList<E> Constructors
ArrayList<E> ( )
ArrayList<E> (int capacity)
Creates an empty
ArrayList<E> of
default capacity (ten)
Java docs use the letter E as
the type parameter for elements
in generic collections
Creates an empty
ArrayList<E> of the
specified capacity
12-22
ArrayList<E> Methods
(a Subset)
int size()
boolean isEmpty ()
boolean add (E obj)
void add (int i, E obj)
E set(int i, E obj)
E get(int i)
E remove(int i)
boolean contains(E obj)
int indexOf(E obj)
use equals to
compare objects
i must be from 0 to
size() -1
inserts obj as the
i-th value; i must
be from 0 to size()
returns true
12-23
ArrayList Example
ArrayList<String> names = new ArrayList<String>( );
names.add(“Abdullah");
names.add(“Ali");
names.add(0, "Aysha");
System.out.println(names);
[Abdullah, Ali, Aysha]
Output
ArrayList’s toString
method returns a string of
all the elements, separated
by commas, within [ ].
12-24
ArrayList<E> Details
• Automatically increases (doubles) the capacity
when the list runs out of space (allocates a
bigger array and copies all the values into it).
• get(i) and set(i, obj) are efficient because an
array provides random access to its elements.
• Throws IndexOutOfBoundsException when
i < 0 or i ≥ size()
(or i > size() in add (i, obj) )
12-25
ArrayList<E> Autoboxing
• If you need to put ints or doubles into a list,
use a standard Java array or convert them
into Integer or Double objects
• Conversion from int to Integer and from
double to Double is, in most cases,
automatic (a feature known as autoboxing
or autowrapping); the reverse conversion
(called autounboxing) is also automatic.
12-26
ArrayList<E> Autoboxing
Example
ArrayList<Integer> counts = new
ArrayList<Integer>( );
counts.add(17);
...
int count = counts.get(0);
Autoboxing: compiled as
counts.add(new Integer(17));
Autounboxing: count
gets the value 17
12-27
ArrayList Pitfalls
// Remove all occurences
// of "like" from words:
int i = 0;
while (i < words.size())
{
if ("like".equals(words.get(i))
words.remove(i);
else
i++;
}
for (int i = 0; i < words.size();
i+
+)
{
if ("like".equals(words.get(i))
words.remove(i);
}
Shifts all the
elements after the i-th
to the left and
decrements the size
Caution: when you remove
elements, a simple for loop
doesn’t work:
12-28
“For Each” Loop
• Introduced in Java 5
• Works both with standard arrays and ArrayLists
• You cannot add or remove elements within a
“for each” loop.
• You cannot change elements of primitive data
types or references to objects within a “for
each” loop.
• Convenient for traversing
• Replaces iterators for collections
“For Each” Loop: Example 1
int [ ] scores = { ... };
….
int sum = 0;
for (int s : scores)
{
sum += s;
}
Basically the same as:
for (int i = 0;
i < scores.length; i++)
{
int s = scores[i];
sum += s;
}
12-30
“For Each” Loop: Example 2
ArrayList<String> words = new ArrayList<String>();
...
for (String str : words)
{
System.out.println(str); // process str
}
Basically the same as:
for (int i = 0;
i < words.size(); i++)
{
String str = words.get(i);
System.out.println(str);
}
19-31
Iterator VS “For Each” Loop
Iterator<String> iter = words.iterator();
while (iter.hasNext ())
{
String word = iter.next ();
< ... process word >
}
Collection<String> words = new ArrayList<String>();
...
for (String word : words)
{
< ... process word >
}
A “for each” loop is a
syntactic shortcut that
replaces an iterator

More Related Content

PDF
STL in C++
PPTX
Standard Template Library
PDF
Standard template library
PPTX
How to choose best containers in STL (C++)
PDF
An Introduction to Part of C++ STL
PPTX
Standard template library
PPT
Stl (standard template library)
STL in C++
Standard Template Library
Standard template library
How to choose best containers in STL (C++)
An Introduction to Part of C++ STL
Standard template library
Stl (standard template library)

What's hot (20)

PDF
Collections In Java
PPTX
Data structures in c#
PPTX
Java class 5
PDF
07 java collection
PPTX
Java - Collections framework
PPTX
Java.util
PDF
Collections Api - Java
PDF
Java Collections Tutorials
PDF
C++ Standard Template Library
PDF
An Introduction to Programming in Java: Arrays
PDF
Java Collection framework
PPTX
Java util
PDF
9 python data structure-2
PDF
5 collection framework
PPT
Java collection
PPTX
Collections - Lists & sets
PPTX
Array list(1)
PPTX
Collections
PPTX
Understanding the components of standard template library
Collections In Java
Data structures in c#
Java class 5
07 java collection
Java - Collections framework
Java.util
Collections Api - Java
Java Collections Tutorials
C++ Standard Template Library
An Introduction to Programming in Java: Arrays
Java Collection framework
Java util
9 python data structure-2
5 collection framework
Java collection
Collections - Lists & sets
Array list(1)
Collections
Understanding the components of standard template library
Ad

Viewers also liked (13)

PPTX
Sindrom vygorania vyzov_21_veku
DOCX
Tugas matematika
PDF
Debbie Hopkins “ A qualitative investigation of urban freight delivery in Aot...
PDF
Sea Rotmann “Helping the Behaviour Changers – or how to create systemic chang...
PDF
Malcolm McCulloch "Energy Cultures applied to Energy for Development"
PDF
Phillipa Watson “Getting Bill-Smart: Outcomes of an energy efficiency project...
PPTX
Suhu Dan Pemuaian
PDF
Sara Walton “Lighting in Vanuatu: understanding rapid technological change.”
PPTX
Relaxation of rank-1 spatial constraint in overdetermined blind source separa...
PPTX
Inflection and derivation
PPTX
Presentasi Litosfer
PPTX
Amul butter recent
PPTX
Colgate rural marketing
Sindrom vygorania vyzov_21_veku
Tugas matematika
Debbie Hopkins “ A qualitative investigation of urban freight delivery in Aot...
Sea Rotmann “Helping the Behaviour Changers – or how to create systemic chang...
Malcolm McCulloch "Energy Cultures applied to Energy for Development"
Phillipa Watson “Getting Bill-Smart: Outcomes of an energy efficiency project...
Suhu Dan Pemuaian
Sara Walton “Lighting in Vanuatu: understanding rapid technological change.”
Relaxation of rank-1 spatial constraint in overdetermined blind source separa...
Inflection and derivation
Presentasi Litosfer
Amul butter recent
Colgate rural marketing
Ad

Similar to Java10 Collections and Information (20)

PPTX
collection framework.pptx
PPTX
Lecture 9
PPTX
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
PPTX
VTUOOPMCA5THMODULECollection OverV .pptx
PPTX
mca5thCollection OverViCollection O.pptx
PPTX
VTUOOPMCA5THMODULEvCollection OverV.pptx
PPTX
VTUOOPMCA5THMODULECollection OverVi.pptx
PDF
Array list (java platform se 8 )
PPT
12_-_Collections_Framework
PPT
PPTX
List interface in collections framework
PPTX
arraylist in java a comparison of the array and arraylist
PPTX
collectionsframework210616084411 (1).pptx
PDF
java unit 4 pdf - about java collections
PDF
Lecture 8_٠٨٣٣٣٦taiz unvercity object oreinted programming.pdf
PDF
javacollections.pdf
PPT
Oop lecture7
PPT
Java Collection fundamentals and Uses Unit
PPTX
Nature Activities Binder _ by Slidesgo.pptx
PPTX
Collections lecture 35 40
collection framework.pptx
Lecture 9
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
VTUOOPMCA5THMODULECollection OverV .pptx
mca5thCollection OverViCollection O.pptx
VTUOOPMCA5THMODULEvCollection OverV.pptx
VTUOOPMCA5THMODULECollection OverVi.pptx
Array list (java platform se 8 )
12_-_Collections_Framework
List interface in collections framework
arraylist in java a comparison of the array and arraylist
collectionsframework210616084411 (1).pptx
java unit 4 pdf - about java collections
Lecture 8_٠٨٣٣٣٦taiz unvercity object oreinted programming.pdf
javacollections.pdf
Oop lecture7
Java Collection fundamentals and Uses Unit
Nature Activities Binder _ by Slidesgo.pptx
Collections lecture 35 40

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation theory and applications.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Spectroscopy.pptx food analysis technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Cloud computing and distributed systems.
Encapsulation_ Review paper, used for researhc scholars
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The Rise and Fall of 3GPP – Time for a Sabbatical?
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KodekX | Application Modernization Development
NewMind AI Weekly Chronicles - August'25 Week I
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation theory and applications.pdf
Unlocking AI with Model Context Protocol (MCP)
Spectroscopy.pptx food analysis technology
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
Empathic Computing: Creating Shared Understanding
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Java10 Collections and Information

  • 1. JAVA Software Development Paradigm Advance OO Programming BSCS Semester 6 MCS 3 Course Instructor: Ms. Iram
  • 2. java.util.Random • Benchmarks uses the java.util.Random class — a more controlled way to generate random numbers. • If we set the same seed, we get the same “random” sequence. Random generator1 = new Random(); Random generator2 = new Random(seed); long seed; the seed is different each time int k = generator.nextInt (n); double x = generator.nextDouble (); 0 ≤ k < n 0 ≤ x < 1
  • 3. 13-3 java.util.Arrays • Provides static methods for dealing with arrays. • Works for arrays of numbers, Strings, and Objects. • Methods: int pos = Arrays.binarySearch (arr, target); Arrays.sort (arr); Arrays.fill (arr, value); // fills arr with a given value String str = Arrays.toString(arr); Arrays.asList(arr); Returns a representation of arr as a fixed-length list
  • 4. 13-4 java.util.Collections • Provides static methods for dealing with ArrayLists and other Java collections. • Works for arrays of numbers, Strings, and Objects. • Methods: int pos = Collections.binarySearch (list, target); Collections.sort (list); Collections.shuffle (list);
  • 5. 19-5 Collection, Iterator • Collection interface represents any collection. • An iterator is an object that helps to traverse the collection (process all its elements in sequence). • A collection supplies its own iterator(s), (returned by collection’s iterator method); the traversal sequence depends on the collection. «interface» Collection «interface» Iterator
  • 6. 19-6 Collections • Collection, Iterator • Lists, ListIterator  List  ArrayList  LinkedList • Stack • Queue, PriorityQueue • Sets  Set  TreeSet  HashSet • Maps  Map  TreeMap  HashMap All these interfaces and classes are part of the java.util package. Names of interfaces are in italics.
  • 7. 19-7 Overview «interface» Collection «interface» Iterator «interface» Comparable «interface» Comparator «interface» Queue «interface» Map Stack PriorityQueue HashMapTreeMap LinkedListArrayList TreeSet HashSet «interface» List «interface» Set «interface» ListIterator Collection Set TreeSet HashSet List ArrayList LinkedList TreeSet TreeMap PriorityQueue
  • 8. 19-8 Collection<E> Methods boolean isEmpty () int size () boolean contains (Object obj) boolean add (E obj) boolean remove (E obj) Iterator<E> iterator () // ... other methods Supplies an iterator for this collection «interface» Collection «interface» Iterator
  • 9. 19-9 Iterator<E> Methods boolean hasNext () E next () void remove () «interface» Collection «interface» Iterator What’s “next” is determined by a particular collection Removes the last visited element
  • 10. 19-10 Lists, ListIterator • A list represents a collection in which all elements are numbered by indices: a0, a1, ..., an-1 • java.util:  List interface  ArrayList  LinkedList • ListIterator is an extended iterator, specific for lists (ListIterator is a subinterface of Iterator)
  • 11. 19-11 List<E> Methods «interface» Collection «interface» Iterator «interface» ListIterator «interface» List // All Collection<E> methods, plus: E get (int i) E set (int i, E obj) void add (int i, E obj) E remove (int i) int indexOf (Object obj) ListIterator<E> listIterator () ListIterator<E> listIterator (int i) These methods are familiar from ArrayList, which implements List Returns a ListIterator that starts iterations at index i
  • 12. 19-12 ListIterator<E> Methods «interface» Collection «interface» Iterator «interface» ListIterator «interface» List // The three Iterator<E> methods, plus: int nextIndex () boolean hasPrevious () E previous () int previousIndex () void add (E obj) void set (E obj) Can traverse the list backward Can add elements to the list (inserts after the last visited element) Can change elements (changes the last visited element)
  • 13. 19-13 ArrayList • Represents a list as a dynamic array (array that is resized when full) • Provides random access to the elements • Implements all the methods of List<E> «interface» Iterator «interface» ListIterator «interface» List ArrayList LinkedList a1 a2 an-1...a0
  • 14. 19-14 LinkedList • Represents a list as a doubly-linked list with a header node • Implements all the methods of List<E> a0 a1 a2 an-1 ... «interface» Iterator «interface» ListIterator «interface» List ArrayList LinkedList header
  • 15. 19-15 LinkedList (cont’d) • Additional methods specific to LinkedList: «interface» Iterator «interface» ListIterator «interface» List ArrayList LinkedList void addFirst (E obj) void addLast (E obj) E getFirst () E getLast () E removeFirst () E removeLast ()
  • 16. 19-16 ArrayList vs. LinkedList • Implements a list as an array + Provides random access to the elements - Inserting and removing elements requires shifting of subsequent elements - Needs to be resized when runs out of space • Implements a list as a doubly-linked list with a header node - No random access to the elements — needs to traverse the list to get to the i-th element + Inserting and removing elements is done by rearranging the links — no shifting + Nodes are allocated and released as necessary
  • 17. 12-19 java.util.ArrayList<E> • Implements a list using an array. • Can only hold objects (of a specified type), not elements of primitive data types. • Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list) "Cat" "Hat" "Bat" capacity size ...
  • 18. 12-20 ArrayList  Generics • Starting with Java 5, ArrayList and other collection classes hold objects of a specified data type. • The elements’ data type is shown in angle brackets and becomes part of the ArrayList type. For example: ArrayList<String> words = new ArrayList<String>(); ArrayList<Integer> nums = new ArrayList<Integer>();
  • 19. 12-21 ArrayList<E> Constructors ArrayList<E> ( ) ArrayList<E> (int capacity) Creates an empty ArrayList<E> of default capacity (ten) Java docs use the letter E as the type parameter for elements in generic collections Creates an empty ArrayList<E> of the specified capacity
  • 20. 12-22 ArrayList<E> Methods (a Subset) int size() boolean isEmpty () boolean add (E obj) void add (int i, E obj) E set(int i, E obj) E get(int i) E remove(int i) boolean contains(E obj) int indexOf(E obj) use equals to compare objects i must be from 0 to size() -1 inserts obj as the i-th value; i must be from 0 to size() returns true
  • 21. 12-23 ArrayList Example ArrayList<String> names = new ArrayList<String>( ); names.add(“Abdullah"); names.add(“Ali"); names.add(0, "Aysha"); System.out.println(names); [Abdullah, Ali, Aysha] Output ArrayList’s toString method returns a string of all the elements, separated by commas, within [ ].
  • 22. 12-24 ArrayList<E> Details • Automatically increases (doubles) the capacity when the list runs out of space (allocates a bigger array and copies all the values into it). • get(i) and set(i, obj) are efficient because an array provides random access to its elements. • Throws IndexOutOfBoundsException when i < 0 or i ≥ size() (or i > size() in add (i, obj) )
  • 23. 12-25 ArrayList<E> Autoboxing • If you need to put ints or doubles into a list, use a standard Java array or convert them into Integer or Double objects • Conversion from int to Integer and from double to Double is, in most cases, automatic (a feature known as autoboxing or autowrapping); the reverse conversion (called autounboxing) is also automatic.
  • 24. 12-26 ArrayList<E> Autoboxing Example ArrayList<Integer> counts = new ArrayList<Integer>( ); counts.add(17); ... int count = counts.get(0); Autoboxing: compiled as counts.add(new Integer(17)); Autounboxing: count gets the value 17
  • 25. 12-27 ArrayList Pitfalls // Remove all occurences // of "like" from words: int i = 0; while (i < words.size()) { if ("like".equals(words.get(i)) words.remove(i); else i++; } for (int i = 0; i < words.size(); i+ +) { if ("like".equals(words.get(i)) words.remove(i); } Shifts all the elements after the i-th to the left and decrements the size Caution: when you remove elements, a simple for loop doesn’t work:
  • 26. 12-28 “For Each” Loop • Introduced in Java 5 • Works both with standard arrays and ArrayLists • You cannot add or remove elements within a “for each” loop. • You cannot change elements of primitive data types or references to objects within a “for each” loop. • Convenient for traversing • Replaces iterators for collections
  • 27. “For Each” Loop: Example 1 int [ ] scores = { ... }; …. int sum = 0; for (int s : scores) { sum += s; } Basically the same as: for (int i = 0; i < scores.length; i++) { int s = scores[i]; sum += s; }
  • 28. 12-30 “For Each” Loop: Example 2 ArrayList<String> words = new ArrayList<String>(); ... for (String str : words) { System.out.println(str); // process str } Basically the same as: for (int i = 0; i < words.size(); i++) { String str = words.get(i); System.out.println(str); }
  • 29. 19-31 Iterator VS “For Each” Loop Iterator<String> iter = words.iterator(); while (iter.hasNext ()) { String word = iter.next (); < ... process word > } Collection<String> words = new ArrayList<String>(); ... for (String word : words) { < ... process word > } A “for each” loop is a syntactic shortcut that replaces an iterator

Editor's Notes

  • #3: In this program we want to be “fair” and run each sorting algorithm on the same set of “random” data. We use the java.util.Random class, which allows us to generate the same “random” sequence several times.
  • #4: Needs import java.util.Arrays; The Arrays class is not in the AP subset. All methods in Arrays are static; you cannot instantiate this class.
  • #5: Needs import java.util.Collections; The Collections class is not in the AP subset.
  • #6: Collection uses Iterator. A programmer can obtain two iterators from a collection and use them in nested loops.
  • #7: The most common way to use the collections framework is to create objects of library classes in your programs. However, you can also extend library classes and write your own classes that implement library interfaces.
  • #8: Some connections are not shown here because they muddy the concepts. For example, the Queue interface extends the Collection interface, but we want to use queues in a “pure” way, using only the four queue-specific methods: isEmpty, add, remove, peek. The same for Stack: strictly speaking it implements Collection, but we want to use only the four “pure stack” methods (isEmpty, push, pop, peek).
  • #9: These are the most abstract methods that make sense for any collection. The contains method has to compare objects in some way. The comparison can be based on equals, compareTo, or some other method  this depends on specific implementation. For example, TreeSet uses compareTo (or a comparator); HashSet uses equals (and the hashCode method).
  • #10: next throws an exception if there are no elements left.
  • #11: A list can hold duplicate values.
  • #12: boolean add(E obj) is inherited from Collection, along with isEmpty, size, remove(E obj), iterator, etc. That is why add(obj) and add(i, obj) have different return types.
  • #13: nextIndex returns the index of the element that will be returned by the next call to next. To traverse a list backward: List&amp;lt;String&amp;gt; list = new LinkedList&amp;lt;String&amp;gt;(); ... ListIterator&amp;lt;String&amp;gt; iter = list.listIterator(list.size()); while (iter.hasPrevious()) System.out.println(iter.previous());
  • #14: Recall that the List interface extends Collection, so ArrayList also implements all the methods of Collection.
  • #15: The nodes of a doubly-linked list can be scattered in memory, but each node has references to the next and the previous node. The header node holds the pointers to the first and last nodes of the list. It is convenient to have this “dummy” node: it simplifies code for inserting and removing elements.
  • #16: You need to declare specifically a LinkedList to use these methods. List&amp;lt;String&amp;gt; list = new LinkedList&amp;lt;String&amp;gt;(); ... list.addFirst(str); // syntax error! — doesn’t work! You need: LinkedList&amp;lt;String&amp;gt; list = new LinkedList&amp;lt;String&amp;gt; (); ... list.addFirst(str); // Works!
  • #17: An ArrayList may waste some space, if its capacity is greater than its size. On the other hand, a node of a LinkedList, in addition to a reference to an object (its value) holds references to the next and previous nodes, so a LinkedList takes 3 times more space than a full ArrayList. This is not very important, because the values themselves usually take much more memory.
  • #18: Usually the array that holds the ArrayList’s values has room to add a value at the end. In that case, list.add(obj) takes O(1) time.
  • #19: So if your method receives a List parameter, and you don’t know whether it is an ArrayList or a LinkedList, use a “for each” loop or an iterator.
  • #20: java.util.ArrayList&amp;lt;E&amp;gt; implements java.util.List&amp;lt;E&amp;gt;. Another implementation of List is java.util.LinkedList&amp;lt;E&amp;gt; (Chapter 20). As opposed to a regular array, ArrayList’s methods check that an index is from 0 to size() - 1, not just from 0 to capacity - 1.
  • #21: We would prefer to call them “type-specific collections” rather than “generic collections.”
  • #22: If you know the maximum size of the list ahead of time, it is better to use the second constructor to avoid reallocation of the array and copying its elements. This constructor is not in the AP subset, though. The third constructor (not shown) creates an ArrayList from a given collection.
  • #23: Unfortunately, the two overloaded add methods have different return types. add(obj) is inherited form Collection, while add(i, obj) is specific to List. Perhaps “insert” would be a better name for the latter. contains tells you whether the list contains an object that equals to obj, but it does not tell you its position. This method is also inherited from Collection. indexOf is more specific to List: it returns the index of the first occurrence of obj in List (again, using equals for comparison), or -1 if not found.
  • #24: When an element is inserted, the indices of all the subsequent elements are incremented by 1, and the size is incremented by 1.
  • #25: Object[] temp = items[2 * items.length]; for (int i = 0; i &amp;lt; size(); i++) temp[i] = items[i]; items = temp; Something like the above code is executed automatically when necessary. The old array is picked by the garbage collector.
  • #26: Autoboxing/unboxing is inefficient; in the “real world” values of primitive data types are usually stored in standard arrays.
  • #27: Autounboxing is equivalent to calling the intValue method for an Integer or the doubleValue method for a Double. For example: int count = counts.get(0).intValue();
  • #28: It is a common mistake to forget that remove(i) and add(i, obj) shift the values that follow the i-th element and change their indices. These two methods also change the size of the list.
  • #29: An iterator is an object that helps to traverse a collection. It has a method next that supplies the next element of the collection. A “For each” loop is a shortcut for an iterator.
  • #30: Thus the “for each” loop has been added to Java 5 simply for convenience.
  • #31: Strictly speaking, a “for each” loop is a syntactic shortcut for traversing a list using an iterator (Chapter 19), not indices.
  • #32: Compiler error messages for “for each” loops often mention iterators. You cannot remove elements in a “for each” loop; use an iterator for that.