collections in java

46

Upload: xarles

Post on 17-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

COLLECTIONS IN JAVA. A collection is an object that represents a group of objects. Collection frame work is a unified architecture for representing and manipulating collections, which contains- interfaces, implementations, algorithms. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: COLLECTIONS IN JAVA
Page 2: COLLECTIONS IN JAVA

A collection is an object that represents a group of objects.

Collection frame work is a unified architecture for representing and manipulating collections, which contains- interfaces, implementations, algorithms.

Interface refers to a set of named operations that can be invoked by clients.

Interfaces encapsulate different type of collections.

2

Page 3: COLLECTIONS IN JAVA

3

Page 4: COLLECTIONS IN JAVA

The Iterable interface (java.lang.Iterable) is one of the root interfaces of the Java collection classes.

The Collection interface extends Iterable, so all subtypes of Collection also implement the Iterable interface.

4

Page 5: COLLECTIONS IN JAVA

• Implementations are the data objects used to store collections, which implement the interfaces

• Each of the general-purpose implementations (you will see in the following slide) provides all optional operations contained in its interface• Java Collections Framework also provides several special-purpose implementations for situations

that require nonstandard performance, usage restrictions, or other unusual behavior

5

Page 6: COLLECTIONS IN JAVA

6

Page 7: COLLECTIONS IN JAVA

7

Page 8: COLLECTIONS IN JAVA

SET: It is a collection that cannot duplicate elements.

SORTED SET:It maintains its elements in the ascending order

They are naturally ordered sets. All the elements must be mutually

comparable. Ex: Wordlists , Membership rolls.

8

Page 9: COLLECTIONS IN JAVA

LIST: It is an ordered collection(also known as sequence). It can contain duplicate elements. List interface provides methods to efficiently

insert and remove multiple elements at any arbitarary point in the list.

QUEUE:It is used to hold multiple elements prior to processing. It also provides additional insertion, extraction

and inspection operations. FIFO-First In First Out. Ex: Count down Timer.

9

Page 10: COLLECTIONS IN JAVA

MAP: It provides a more general way of storing elements.

It cannot contain duplicate keys. Maps keys to values. Each key can map

to utmost one value. The Java platform contains three general-

purpose Map implementations:HashMap, TreeMap and LinkedHashMap.

SORTED MAP: It maintains mapping in ascending key order.

It is naturally ordered collection of key/value pairs.

Ex: Dictionaries, Telephone directories.

10

Page 11: COLLECTIONS IN JAVA

The primary advantages of a collections framework are that it:

Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself.

Increases performance by providing high-performance implementations of useful data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations.

Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.

Reduces the effort required to learn APIs by eliminating the need to learn multiple ad hoc collection APIs.

Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.

Fosters software reuse by providing a standard interface for collections and algorithms to manipulate them.

11

Page 12: COLLECTIONS IN JAVA

Collection Advantages and Disadvantages

Advantages• Can hold different types of objects• Resizable

×Disadvantages• Must cast to correct type• Cannot do compile-time type checking.

12

Page 13: COLLECTIONS IN JAVA

The List interface corresponds to an ordered group of elements.

List store a group of elements. It will allow the duplicate values.

Ex: ArrayLists, LinkedLists , Vectors

13

Page 14: COLLECTIONS IN JAVA

An ArrayList is like an array which can grow in memory dynamically.

ArrayList is not synchronized. Creating ArrayList: ArrayList <E> arl=new ArrayList<E>(); Elements can be accessed directly via

the get and set methods.

14

Page 15: COLLECTIONS IN JAVA

Being synchronized means that every operation is thread safe - if you use the same vector from two threads at the same time, they can't corrupt the state. However, this makes it slower.

If you are working in a single threaded environment (or the list is limited to a thread and never shared), use ArrayList. If you are working with multiple threads that share the same collection, either use Vector, or use ArrayList but synchronize in some other way (e.g., manually or via a wrapper).

Vectors are synchronized. Any method that touches the Vector's contents is thread safe.

ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe.

15

Page 16: COLLECTIONS IN JAVA

Some of the ArrayList class methods are :

1. boolean add(element obj): Appends the specified element to the end of the

ArrayList.If the elements is added successfully it returns true.

2. void add(int position,element obj) Inserts the specified element at the specified

position in the ArrayList.

3. element remove(int position) Removes the element at the specified position in

the ArrayList.It returns the removed element.

16

Page 17: COLLECTIONS IN JAVA

4. boolean remove(Object obj): Removes the first occurrence of the

specified element obj from the ArrayList.

5. void clear(): Removes all the elements from the

ArrayList.

6. element set(int position, element obj) Replaces an element at the specified

position in the ArrayList with the new element obj.

17

Page 18: COLLECTIONS IN JAVA

7. boolean contains(Object obj) This method returns true if the

ArrayList contains the specified element obj.

8. element get(int position) Returns the element available at at

the specified position in the ArrayList.9. int size() Returns the number of elements

present in the ArrayList.

18

Page 19: COLLECTIONS IN JAVA

A vector also stores elements(objects) similar to ArrayList. But vector is synchronized.

Creating a vector: Vector<E> v=new Vector<E>(int

capacity);

19

Page 20: COLLECTIONS IN JAVA

Some of the vector class methods are:

1. boolean add(element obj) 2. void add(int position,element obj) 3. element remove(int position) 4. boolean remove(Object obj) 5. void clear() 6. element set(int position,element obj) 7. boolean contains(Object obj) 8. element get(int position) 9. int size()

20

Page 21: COLLECTIONS IN JAVA

In this example we are going to show the use of java.util.Vector class. We will be creating an object

of Vector class and performs various operation like adding, removing etc. Vector class extends

AbstractList and implements List, RandomAccess, Cloneable, Serializable. The size of a vector

increase and decrease according to the program. Vector is synchronized.

In this example we are using seven methods of a Vector class.add(Object o): It adds the element in the end of the Vectorsize(): It gives the number of element in the vector.elementAt(int index): It returns the element at the specified index.firstElement(): It returns the first element of the vector.lastElement(): It returns  last element.removeElementAt(int index): It deletes the element from the given index.elements(): It returns an enumeration of the elementIn this example we have also used Enumeration interface to retrieve the value of a vector.

Enumeration interface has two methods.hasMoreElements(): It checks if this enumeration contains more elements or not.nextElement(): It checks the next element of the enumeration.Code of this program is given in next slide:  21

Page 22: COLLECTIONS IN JAVA

package myArrayList;//java.util.Vector and java.util.Enumeration;

import java.util.*;public class VectorDemo{ public static void main(String[] args){ Vector<Object> vector = new Vector<Object>(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "Amit Mathur"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("The elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The element at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is: " + vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2); System.out.println("The elements of vector after removing: " + vector); System.out.println("Printing elements through Enumerator"); Enumeration e=vector.elements(); System.out.println("The elements are: "); while(e.hasMoreElements()){ System.out.println(e.nextElement()); } }}

22

Page 23: COLLECTIONS IN JAVA

A linked list is a data structure that consists of a sequence of data records.

In each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

23

Page 24: COLLECTIONS IN JAVA

Gives better performance on add and remove

Linked lists by themselves do not allow random access to the data.

The benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory.

Linked lists allow insertion and removal of nodes at any point in the list.

24

Page 25: COLLECTIONS IN JAVA

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

25

Page 26: COLLECTIONS IN JAVA

public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean isEmpty();boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator();

// Bulk operationsboolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional

// Array Operations Object[] toArray(); <T> T[] toArray(T[] a); }

26

Page 27: COLLECTIONS IN JAVA

Set is an interface. We need to instantiate a concrete implementation of the interface in order to use it. We can choose between the following Set implementations in the Java Collections API:

1. java.util.EnumSet 2. java.util.HashSet 3. java.util.LinkedHashSet 4. java.util.TreeSet

27

Page 28: COLLECTIONS IN JAVA

An enumeration is created using the new enum keyword.

enum Week {Monday, Tuesday, Wednesday, Thursday,Friday,Saturd

ay,Sunday}

The identifiers Monday, Tuesday, and so on, are called enumeration constants.

Each is implicitly declared as a public, static member of Week.

Their type is the type of the enumeration in which they are declared.

These constants are called self-typed. 28

Page 29: COLLECTIONS IN JAVA

You declare and use an enumeration variable in much the same way as the primitive types.Week aWeekDay;

Because a WeekDay is of type Week, the only values that it can be assigned (or contain) are those defined by the enumeration.

enum Week {  Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

public class MainClass {  public static void main(String args[]) {    Week aWeekDay;

    aWeekDay = Week.Monday;

    // Output an enum value.    System.out.println("Value of aWeekDay: " + aWeekDay);    System.out.println();  }}

Output :Value of aWeekDay: Monday

29

Page 30: COLLECTIONS IN JAVA

A specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. This representation is extremely compact and efficient.

The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared). The returned iterator is weakly consistent: it may or may not show the effects of any modifications to the set that occur while the iteration is in progress.

Null elements are not permitted. Attempts to insert a null element will throw NullPointerException. Attempts to test for the presence of a null element or to remove one will, however, function properly.

30

Page 31: COLLECTIONS IN JAVA

Like most collection implementations EnumSet is not synchronized. If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum set.

If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet(java.util.Set) method. This is best done at creation time, to prevent accidental unsynchronized access:

Set<MyEnum> s= collections.synchronizedSet(EnumSet.noneOf(Foo.class));

.

31

Page 32: COLLECTIONS IN JAVA

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

This implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the HashSet instance:

Set s = Collections.synchronizedSet(new HashSet(...));

32

Page 33: COLLECTIONS IN JAVA

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.

Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. 33

Page 34: COLLECTIONS IN JAVA

LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. Reinserting an element that is already in the LinkedHashSet does not change this order.

TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.

34

Page 35: COLLECTIONS IN JAVA

Maps provide a more general way of storing elements. The Map collection type allows you to store pairs of

elements, termed "keys" and "values", where each key maps to one value.

The java.util.Map interface represents a mapping between a key and a value.

The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.

35

Page 36: COLLECTIONS IN JAVA

Since Map is an interface you need to instantiate a concrete implementation of the interface in order to use it.

You can choose between the following Map implementations in the Java Collections API:

java.util.HashMap java.util.HashTable java.util.EnumMap java.util.Properties java.util.TreeMap the most commonly used Map

implementations are HashMap and TreeMap36

Page 37: COLLECTIONS IN JAVA

HashMap is a collection that stores elements in the form of key-value pairs. key should be unique. It is not synchronized

Here are a few examples of how to create a Map instance:

Map mapA = new HashMap(); Map mapB = new TreeMap(); Creating HashMap: HashMap<k,v> hm=new HashMap<k,v>();

37

Page 38: COLLECTIONS IN JAVA

To add elements to a Map you call its put() method. Example:

Map mapA = new HashMap();

mapA.put("key1", "element 1");

mapA.put("key2", "element 2");

mapA.put("key3", "element 3"); The three put() calls maps a string value to a string key.

You can then obtain the value using the key.

38

Page 39: COLLECTIONS IN JAVA

To do that you use the get() method like this:

String element1 = (String) mapA.get("key1"); You can iterate either the keys or the values of a Map. // key iterator

Iterator iterator = mapA.keySet().iterator();

keySet():Returns a Set view of the keys contained in the map.

// value iterator

Iterator iterator = mapA.values();

Values():Returns a Collection view of the values contained in the map. 39

Page 40: COLLECTIONS IN JAVA

clear() Removes all mappings from the map. remove(Object key) Removes the key and associated

value from the map. put(Object key, Object value) Associates the

specified value with the specified key. get(Object key) getting values associated with key. putAll(Map t) Copies all of the mappings from the

specified map to this map.

40

Page 41: COLLECTIONS IN JAVA

By default you can put any Object into a Map, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a Map.

example: Map<String, MyObject> map = new HashSet<String,

MyObject>();

This Map can now only accept String objects for keys, and MyObject instances for values.

41

Page 42: COLLECTIONS IN JAVA

Purpose The basic for loop was extended in Java 5 to make iteration

over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each (because it is called this in other programming languages). I've also heard it called the for-in loop.

Use it in preference to the standard for loop if applicable because it's much more readable.

Series of values. The for-each loop is used to access each successive value in a collection of values.

Arrays and Collections. It's commonly used to iterate over an array or a Collections class (eg, ArrayList).

Iterable<E>. It can also iterate over anything that implements the Iterable<E> interface (must define iterator() method). Many of the Collections classes (eg, ArrayList) implement Iterable<E>, which makes the for-each loop very useful. You can also implement Iterable<E> for your own data structures.

42

Page 43: COLLECTIONS IN JAVA

General Form The for-each and equivalent for

statements have these forms. The two basic equivalent forms are given, depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable is required, an index for the array and an iterator for the collection.

43

Page 44: COLLECTIONS IN JAVA

For-each loop Equivalent for loop

for (type var : arr) { body-of-loop} for (int i = 0; i < arr.length; i++) { type var = arr[i]; body-of-loop}

for (type var : coll) { body-of-loop} for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) { type var = iter.next(); body-of-loop}

Example - Adding all elements of an arrayHere is a loop written as both a for-each loop and a basic for loop. double[] ar = {1.2, 3.0, 0.8};int sum = 0; for (double d : ar) { // d gets successively each value in ar. sum += d; } And here is the same loop using the basic for. It requires an extra iteration variable.double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (int i = 0; i < ar.length; i++) { // i indexes each element successively. sum += ar[i]; } 44

Page 45: COLLECTIONS IN JAVA

Although the enhanced for loop can make code much clearer, it can't be used in some common situations.

Only access. Elements can not be assigned to, eg, not to increment each element in a collection.

Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.

Only single element. Use only for single element access, eg, not to compare successive elements.

Only forward. It's possible to iterate only forward by single steps.

At least Java 5. Don't use it if you need compatibility with versions before Java 5.

45

Page 46: COLLECTIONS IN JAVA

Iterator iterator; iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + "

"); }

46