collections in java
Download
Skip this Video
Download Presentation
COLLECTIONS IN JAVA

Loading in 2 Seconds...

play fullscreen
1 / 46

COLLECTIONS IN JAVA - PowerPoint PPT Presentation


  • 122 Views
  • Uploaded on

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' COLLECTIONS IN JAVA' - xarles


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
introduction

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.
INTRODUCTION
slide4

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.

implementations

• 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

Implementations
slide8

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.
slide9

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.
slide10

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.
slide11

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.
slide12

Collection Advantages and Disadvantages

    • Advantages

• Can hold different types of objects

• Resizable

    • Disadvantages

• Must cast to correct type

• Cannot do compile-time type checking.

lists

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

LISTS
arraylists

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.

Arraylists
syncronized vs unsynchronized

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.
Syncronized Vs unsynchronized
slide16

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(intposition,elementobj)

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.

slide17

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.

slide18

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.

vectors

A vector also stores elements(objects)

similar to ArrayList.

But vector is synchronized.

  • Creating a vector:

Vector<E> v=new Vector<E>(int capacity);

vectors
slide20

Some of the vector class methods are:

  • 1. boolean add(element obj)
  • 2. void add(intposition,elementobj)
  • 3. element remove(int position)
  • 4. boolean remove(Object obj)
  • 5. void clear()
  • 6. element set(intposition,elementobj)
  • 7. boolean contains(Object obj)
  • 8. element get(int position)
  • 9. int size()
vector example 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 Vector

size(): 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 element

In 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: 

Vector Example in java
slide22

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

}

}

}

linked lists

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.

Linked lists
slide24

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.

set interface

A Setis 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.
Set interface
the set interface code

public interface Set<E> extends Collection<E> {

// Basic operations

int size();

booleanisEmpty();

boolean contains(Object element);

boolean add(E element); //optional

boolean remove(Object element); //optional

Iterator<E> iterator();

// Bulk operations

booleancontainsAll(Collection<?> c);

booleanaddAll(Collection<? extends E> c); //optional

booleanremoveAll(Collection<?> c); //optional

booleanretainAll(Collection<?> c); //optional

void clear(); //optional

// Array Operations

Object[] toArray();

<T> T[] toArray(T[] a);

}

The Set Interface COde
set implementations

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:

java.util.EnumSet

java.util.HashSet

java.util.LinkedHashSet

java.util.TreeSet

SET IMPLEMENTATIONS
enum data types

An enumeration is created using the new enum keyword.

enumWeek {

Monday, Tuesday, Wednesday, Thursday,Friday,Saturday,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.
Enum data types
enum data types1

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

Enum data types
what is an enum set

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.
What is an Enum set?
enum set contd

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

.

ENUM SET (Contd.)
hash set

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

HASH SET
hash set contd

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.

Hash set (contd.)
linked hash set tree set

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.
LINked hash set & Tree set
slide35

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.

maps
map implementations

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 TreeMap
Map Implementations
hashmap

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

Hashmap
adding and accessing elements

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.

Adding and Accessing Elements
slide39

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.

hashmap class methods

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.

HashMap class methods
generic maps

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.

Generic Maps
for each loop

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.
For-each Loop
for each loop1

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.

For-each Loop
slide44

Example - Adding all elements of an array

Here 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]; }

where the for each is appropriate

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.
Where the for-each is appropriate
iterator example

Iterator iterator;

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() + " ");

}

Iterator Example
ad