generics and collection framework · 06/08/2019  · interface (java.util.map) are the two main...

19
Generics and Collection Framework

Upload: others

Post on 24-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Generics and

Collection Framework

Page 2: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Generics

It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering.

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.

You can think of them as a template

The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.

Page 3: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Generic Methods

You can write a single generic method declaration that can be called with arguments of different types.

Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.

Following are the rules to define Generic Methods −

Generic methods have a type parameter (the diamond operator enclosing the type) before the return type of the method declaration

Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

The type parameters can be used to declare the return type as well as for the method paameters

A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).

Page 4: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Example Code

Page 5: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Generic Classes

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.

These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

Page 6: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Example Code

Page 7: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Advantages of using Generics

Code Reuse: We can write a method/class/interface once and use for any type we want.

Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time).

Suppose you want to create an ArrayList that store name of students

and if by mistake programmer adds an integer object instead of string,

compiler allows it. But, when we retrieve this data from ArrayList, it

causes problems at runtime.

Page 8: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Collection Framework

A Collection is a group of individual objects represented as a single unit.

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.

Need for Collection Framework :

Before Collection Framework (or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors or Hashtables. All of these collections had no common interface.

Accessing elements of these Data Structures was a hassle as each had a different method (and syntax) for accessing its members

Page 9: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Advantages of Collection Framework

Consistent API

The API has a basic set of interfaces like Collection, Set, List, or Map. All classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods.

Reduces programming effort

A programmer doesn’t have to worry about the design of Collection, and he can focus on its best use in his program.

Increases program speed and quality

Increases performance by providing high-performance implementations of useful data structures and algorithms.

Page 10: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Collection Framework

Collection : Root interface with basic methods like add(), remove(), contains(), isEmpty(), addAll(), ... etc.

Set : Doesn't allow duplicates. Example implementations of Set interface are HashSet (Hashing based) and TreeSet (balanced BST based). Note that TreeSetimplements SortedSet.

List : Can contain duplicates and elements are ordered. Example implementations are LinkedList (linked list based) and ArrayList (dynamic array based)

Queue : Typically order elements in FIFO order except exceptions like PriorityQueue.

Deque : Elements can be inserted and removed at both ends. Allows both LIFO and FIFO.

Map : Contains Key value pairs. Doesn't allow duplicates. Example implementation are HashMap and TreeMap. TreeMap implements SortedMap.

Page 11: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before
Page 12: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

ArrayList

ArrayList is a part of collection framework and is present in java.utilpackage. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

ArrayList inherits AbstractList class and implements List interface.

ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if objects are removed from the collection.

Java ArrayList allows us to randomly access the list.

ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.

Page 13: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Working with ArrayList

Constructors in Java ArrayList:

ArrayList(): This constructor is used to build an empty array list

ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from collection c

ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified

Creating generic integer ArrayList

ArrayList<Integer> arrli = new ArrayList<Integer>();

Page 14: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Contd.

Adding elements in List

arrli.add(1)

Removing elements from list at a particular index

arrli.remove(int index)

Removing elements from list

arrli.remove(Object o)

Get size of list

arrli.size()

Get the element at the specified position in this list

get(int index)

Page 15: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Some other methods set (int index, E element): Replaces the element at the specified position in this list with the specified element.

removeAll (Collection c): Removes from this list all of its elements that are contained in the specified collection.

listIterator (): Returns a list iterator over the elements in this list (in proper sequence).

listIterator (int index): Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

isEmpty (): Returns true if this list contains no elements.

removeRange (int fromIndex, int toIndex): Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.

void clear(): This method is used to remove all the elements from any list.

void add(int index, Object element): This method is used to insert a specific element at a specific position index in a list.

int indexOf(Object O): The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list.

int lastIndexOf(Object O): The index the last occurrence of a specific element is either returned, or -1 in case the element is not in the list.

boolean addAll(Collection C): This method is used to append all the elements from a specific collection to the end of the mentioned list, in such a order that the values are returned by the specified collection’s iterator.

boolean add(Object o): This method is used to append a specificd element to the end of a list.

boolean addAll(int index, Collection C): Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.

Page 16: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Iterators

Iterators are used in Collection framework in Java to retrieve elements

one by one.

Iterator

It is a universal iterator and can be applied to any Collection object.

By using Iterator, we can perform both read and remove operations.

Iterator must be used whenever we want to enumerate elements in all

Collection framework implemented interfaces like Set, List, Queue,

Deque and also in all implemented classes of Map interface.

Iterator is the only cursor available for entire collection framework.

Iterator object can be created by calling iterator()method present in

Collection interface.

Page 17: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Using Iterator

Creating an iterator object

// Here "c" is any Collection object.

//itr is of type Iterator interface and refers to "c"

Iterator itr = c.iterator();

Iterator has following methods:

public boolean hasNext();

❑ Returns true if the iteration has more elements

public Object next();

❑ Returns the next element in the iteration and throws NoSuchElementException if no more elements arr present

public void remove();

❑ Remove the next element in the iteration. This method can be called only once per call to next()

Page 18: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Example

Code

Page 19: Generics and Collection Framework · 06/08/2019  · interface (java.util.Map) are the two main “root” interfaces of Java collection classes. Need for Collection Framework : Before

Thank You!