java10 collections and information
TRANSCRIPT
JAVA Software Development Paradigm Advance OO Programming
BSCS Semester 6MCS 3Course 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 valueString 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
HashMap TreeMap
LinkedList ArrayList 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 thei-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"
capacitysize
...
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]
OutputArrayList’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 wheni < 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 ascounts.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