java10 collections and information

29
JAVA Software Development Paradigm Advance OO Programming BSCS Semester 6 MCS 3 Course Instructor: Ms. Iram

Upload: softnutx

Post on 11-Jan-2017

141 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Java10 Collections and Information

JAVA Software Development Paradigm Advance OO Programming

BSCS Semester 6MCS 3Course Instructor: Ms. Iram

Page 2: Java10 Collections and Information

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

Page 3: Java10 Collections and Information

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

Page 4: Java10 Collections and Information

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

Page 5: Java10 Collections and Information

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

Page 6: Java10 Collections and Information

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.

Page 7: Java10 Collections and Information

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

Page 8: Java10 Collections and Information

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

Page 9: Java10 Collections and Information

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

Page 10: Java10 Collections and Information

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)

Page 11: Java10 Collections and Information

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

Page 12: Java10 Collections and Information

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)

Page 13: Java10 Collections and Information

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

Page 14: Java10 Collections and Information

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

Page 15: Java10 Collections and Information

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

Page 16: Java10 Collections and Information

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

Page 17: Java10 Collections and Information

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

...

Page 18: Java10 Collections and Information

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

Page 19: Java10 Collections and Information

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

Page 20: Java10 Collections and Information

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

Page 21: Java10 Collections and Information

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 [ ].

Page 22: Java10 Collections and Information

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

Page 23: Java10 Collections and Information

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.

Page 24: Java10 Collections and Information

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

Page 25: Java10 Collections and Information

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:

Page 26: Java10 Collections and Information

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

Page 27: Java10 Collections and Information

“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;}

Page 28: Java10 Collections and Information

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

Page 29: Java10 Collections and Information

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