Java Collections Generics

40
By Waqas 1 Java Collections and Generics java.util package

description

This is from sun. It explains the Interfaces and Classes from the collection and the explanations are really sort and sweet. Given syntax and coding exapmples are useful to visualize the logics and workflow.... I liked it .... hope u also

Transcript of Java Collections Generics

Java Collections and Genericsjava.util packageBy Waqas 1

Java Collection Framework Collection Framework Elements Collection Framework Interfaces Collection Interface Set Interface List Interface SortedSet Interface Map Interface SortedMap Interface Collection Framework Implementations ArrayList Class LinkedList Class HastSet Class TreeSet Class HashMap Class TreeMap Class

Comparable Interface Arrays Class Comparator Interface Collections Class Generics in Java Examples of Generic Errors Generic ArrayList Generic TreeSet Generic TreeMap Generic Iterator

By Waqas

2

Java Collection FrameworkA Collection (sometimes called a Container) is simply an object that groups multiple objects into a single group.

The java collection framework standardizes the way in which groups of objects are handled by your programs by providing a unified architecture called Collection FrameworkBy Waqas 3

The Collection Framework is designed to meet several goals.

First, the framework provides high performance, fast and highly efficient way to work with groups of objects.

Second, the framework allows different types of collections to work in a similar manner with highBy Waqas 4

Collection Framework ElementsThe Collection Framework consists of elements: Interfaces, Implementation Algorithms. three and

InterfacesAbstract data types to manipulate collections independent of implementation Collection, Set, List, Map etc.By Waqas

details.

e.g.5

ImplementationsConcrete classes which are implementing

Collection interfaces, used as reusable data structures. e.g. HashMap, ArrayList, TreeSet, HashSet etc.

AlgorithmsMethods to perform operations on collectionsBy Waqas such as sorting, searching, iterations. 6

Collection Framework Interfaces

By Waqas

7

Collection

Map

Set

List

SortedMap

SortedSet

Collection Framework

InterfacesBy Waqas 8

Collection InterfaceA Collection interface is the super interface in the collection interfaces hierarchy. A collection represents a group of objects, known as its elements. Java does not provide any direct implementation of this interface. It provides implementations of more specific subinterfaces like Set and List.By Waqas 9

Set InterfaceA Set is a Collection that does not contain duplicate elements, so its a collection of unique elements. If you add duplicate element in Set then add( ) method simply ignore the element and return false. The elements in Set are not in order. The set interface does not define any additional methods, it inherits all the methods of Collection interface.By Waqas

10

List InterfaceThe List interface also extends Collection interface and declares the behavior of a collection that stores a sequence of objects in order. Elements can be inserted or retrieved by their position in the list, using a zero based index. List can accept duplicate values.

By Waqas

11

SortedSet InterfaceThe SortedSet interface extends Set and declares the behavior of a set in which objects are sorted in either their natural order or the order you specified in your custom object. SortedSet does not accept duplicate elements.

By Waqas

12

Map InterfaceA Map is an object that maps keys to values. A map cannot contain duplicate keys but can contain duplicate values. Each key can map to at most one value. We can retrieve value by using its key. Elements are not orderedBy Waqas13

SortedMap InterfaceThe SortedMap interface extends Map and declares the behavior of a map in which objects are sorted by their keys in their natural order or custom order.

SortedMap elements can not contain duplicate keys.

By Waqas

14

Difference between InterfacesInterface Set List Map Duplicates Not Allowed Allowed Not Allowed for Keys Order No Order Order by Index No Order Sorting No Sorting No Sorting No Sorting

Sorted Set Sorted Map

Not Allowed Not Allowed

By Natural Order By Natural Order

By Natural Order By Natural Order

By Waqas

15

Collection Framework Implementations

By Waqas

16

Set

SortedSet

List

HashSet

TreeSet

ArrayList Vector

LinkedList

Map

SortedMap

HashMap

TreeMapBy Waqas

Collection Framework Implementations17

ArrayList ClassArrayList class implements the List interface. ArrayList is a dynamic array that can grow and shrink automatically as needed. Insertions and deletions are linear thats why these operations are slow in ArrayList Searching is fast in ArrayList because Java performs search randomly.By Waqas

18

LinkedList ClassLinkedList class implements the List interface. Every element in LinkedList contains the data item and the pointer to the next node. Insertions and deletions are fast because they are linear in time. Searching is slow as java search LinkedList sequentially not randomly.By Waqas

19

HashSet ClassHastSet provides an implementation of Set

interface. Objects are not stored in order thats why searching objects is very fast.

HashSet does not support duplicate elements.By Waqas 20

TreeSet ClassTreeSet provides an implementation of SortedSet interface. Objects are stored in sorted, ascending order. Access and retrieval times is not as fast as HashSet. TreeSet is an excellent choice when you want to store large amounts of sorted data items.By Waqas 21

HashMap ClassHashMap provides an implementation of Map interface. Objects are stored as key-value pairs. null objects are supported by the HashMap. Objects are not stored in order.

By Waqas

22

TreeMap ClassTreeMap class implements SortedMap interface. It provides an efficient means of storing key-value pairs in sorted order based on their keys.

As objects are sorted so random access or searching is little slower then HashMap.By Waqas 23

Comparable InterfaceMany java collection framework classes such as TreeMap, TreeSet perform automatic sorting of objects when they added in the collection. For sorting objects they must be comparable. Java provides an interface to make two objects comparable. Custom classes should implement comparable interface to provide logic for class specific sortingBy Waqas

24

Comparable Interfaceclass Student implements Comparable { int id; public int compareTo(Object obj) { Student s2 = (Student) obj; Integer st1 = new Integer(this.id); Integer st2 = new Integer(s2.id); return st1.compareTo(st2); By Waqas

25

Arrays ClassArrays class contains manipulating arrays. various methods for

The two most common methods are sorting and searching. To sort array pass the array in the sort method. This method sort all elements in their natural order. To search elements inside array use binarySearch 26 By Waqas method.

Comparator InterfaceComparator interface is used to create objects which can be passed to Arrays.sort or Collection.sort methods or collections such as TreeMap and TreeSet. They are used to sort custom objects in collections. They are not needed for arrays and collections of primitive data types and for objects that have a natural sorting order such as String, Integer.By Waqas

27

Comparator Interfaceclass StudentComparator implements Comparator { public int compare(Object obj1, Object obj2) { Student s1 = (Student) obj1; Student s2 = (Student) obj2; Integer st1 = new Integer(s1.id); Integer st2 = new Integer(s2.id);By Waqas 28

Comparator InterfaceStudent students[] = new Student[5]; students[0] students[1] students[2] students[3] students[4] = = = = = new new new new new Student(5, Student(2, Student(1, Student(4, Student(3, "Simon"); "James"); "Peter"); "David"); "John");

By Waqas Arrays.sort(students, new

29

Collections ClassCollections class contains various methods for manipulating collections.

sort( List ); binarySearch( List, Object ); min(List); max(List); replaceAll(List, Object, Object); reverse(List); shuffle(List); swap(List, int, int);By Waqas 30

Java Generics

By Waqas

31

Example of Generic ErrorsWhen we retrieve an element from a collection, we need to cast it to the right type otherwise compile time error occur.ArrayList list = new ArrayList(); String input = London; list.add(input); String output = list.get(0); // Compiler Error

String output = (String) list.get(0); // ValidBy Waqas 32

Example of Generic ErrorsThere is no way to ensure that we are casting to a correct type. Following code will compile but it will throw exception at runtime.ArrayList list = new ArrayList(); String input = London; list.add(input);

Integer output = list.get(0); // Runtime Error

By Waqas

33

Java GenericsGenerics in Java allow us to create collections with a strong type. This means that if we are creating a collection to store Strings we will be forced to store and retrieve only Strings at compile time and runtime. Overall result of using generics in java collections is improved reliability, readability and performance.By Waqas 34

Generic ArrayListArrayList list = new ArrayList(); ArrayList list = new ArrayList(); list.add(Simon); list.add(Peter); list.add(new Integer(2)); String s1 = list.get(0); String s2 = list.get(1); Integer I = list.get(0); // Compiler Error // Compiler Error

By Waqas

35

Generic TreeSetTreeSet set = new TreeSet();

>();TreeSet set = new TreeSet();TreeMap map = new TreeMap();TreeSet set = new TreeSet