You are on page 1of 29

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
the seed is different
numbers.
Random generator1 = new Random();
Random generator2 = new Random(seed);

each time

long seed;

If we set the same seed, we get the same


random sequence.
int k = generator.nextInt (n);

0k<n

double x = generator.nextDouble ();

0x<1

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-3

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);

13-4

Collection, Iterator
interface
Iterator

interface
Collection

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 collections iterator method); the
traversal sequence depends on the
collection.
19-5

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-6

Overview

19-7

Collection<E>
Methods
boolean isEmpty ()
int size ()
boolean contains (Object obj)
boolean add (E obj)
boolean remove (E obj)
Iterator<E> iterator ()
// ... other methods

interface
Iterator

interface
Collection

Supplies an
iterator for this
collection

19-8

Iterator<E>
Methods

interface
Iterator

boolean hasNext ()
E next ()
void remove ()

interface
Collection

Whats next is
determined by a
particular collection

Removes the last


visited element

19-9

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-10

List<E>
Methods

interface
Iterator

interface
Collection

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-11

ListIterator<E>
Methods

interface
Iterator

interface
Collection

interface
ListIterator

interface
List

// The three Iterator<E> methods, plus:


int nextIndex ()
boolean hasPrevious ()
Can traverse the
E previous ()
list backward
int previousIndex ()
void add (E obj)
Can add elements to the list (inserts
void set (E obj)
after the last visited element)
Can change elements (changes
the last visited element)
19-12

interface
List

interface
Iterator

ArrayList

interface
ListIterator

ArrayList

LinkedList

Represents a list as a dynamic array (array that is resized


when full)

Provides random access to the elements


a0

a1

a2

... an-1

Implements all the methods of List<E>

19-13

interface
List

interface
Iterator

LinkedList

interface
ListIterator

ArrayList

LinkedList

Represents a list as a doubly-linked list


with a header node
header
a0

a1

a2

...

an-1

Implements all the methods of List<E>


19-14

LinkedList
(contd)

interface
Iterator

interface
ListIterator

interface
List

ArrayList

LinkedList

Additional methods specific to LinkedList:


void addFirst (E obj)
void addLast (E obj)
E getFirst ()
E getLast ()
E removeFirst ()
E removeLast ()

19-15

ArrayList

vs. LinkedList

Implements a list as an array

Implements a list as a doublylinked list with a header node

+ Provides random access to


the elements

- Inserting and removing


elements requires shifting of
subsequent elements
- Needs to be resized when
runs out of space

- 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

19-16

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)
capacity
size
"Cat"

"Hat"

"Bat"

...
12-19

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-20

ArrayList<E> Constructors
Java docs use the letter E as
the type parameter for elements
in generic collections

ArrayList<E> ( )

Creates an empty
ArrayList<E> of
default capacity (ten)

ArrayList<E> (int capacity)


Creates an empty
ArrayList<E> of the
specified capacity

12-21

ArrayList<E> Methods
(a Subset)
int size()
boolean isEmpty ()
boolean add (E obj)

returns true

void add (int i, E obj)

inserts obj as the


i-th value; i must
be from 0 to size()

E set(int i, E obj)
E get(int i)
E remove(int i)
boolean contains(E obj)
int indexOf(E obj)

i must be from 0 to
size() -1
use equals to
compare objects
12-22

ArrayList Example
ArrayList<String> names = new ArrayList<String>( );
names.add(Abdullah");
names.add(Ali");
names.add(0, "Aysha");
System.out.println(names);
Output

[Abdullah, Ali, Aysha]

ArrayLists toString
method returns a string of
all the elements, separated
by commas, within [ ].

12-23

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-24

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-25

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-26

ArrayList Pitfalls
// Remove all occurences
// of "like" from words:
int i = 0;

Caution: when you remove


elements, a simple for loop
doesnt work:

while (i < words.size())


for (int i = 0; i < words.size();
{
i+
if ("like".equals(words.get(i))
+)
words.remove(i);
{
else
if ("like".equals(words.get(i))
i++;
words.remove(i);
}
}
Shifts all the
elements after the i-th
to the left and
decrements the size
12-27

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
12-28

For Each Loop: Example 1

Basically the same as:


int [ ] scores = { ... };
.
int sum = 0;
for (int s : scores)
{
sum += s;
}

for (int i = 0;
i < scores.length; i++)
{
int s = scores[i];
sum += s;
}

For Each Loop: Example 2

ArrayList<String> words = new ArrayList<String>();


...
for (String str : words)
{
Basically the same as:
System.out.println(str); // process str
}
for (int i = 0;
i < words.size(); i++)
{
String str = words.get(i);
System.out.println(str);
}
12-30

Iterator VS For Each Loop


Collection<String> words = new ArrayList<String>();
...
for (String word : words)
{
< ... process word >
}

A for each loop is a


syntactic shortcut that
replaces an iterator

Iterator<String> iter = words.iterator();


while (iter.hasNext ())
{
String word = iter.next ();
< ... process word >
}

19-31

You might also like