28
GENERIC COLLECTIONS

GENERIC COLLECTIONS. Type-Wrapper Classes Each primitive type has a corresponding type- wrapper class (in package java.lang). These classes are called

Embed Size (px)

Citation preview

Page 1: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

GENERIC COLLECTIONS

Page 2: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Type-Wrapper ClassesEach primitive type has a corresponding type-

wrapper class (in package java.lang). These classes are called Boolean, Byte, Character,

Double, Float, Integer, Long and Short. These enable you to manipulate primitive-type

values as objects.This is important because Java’s predefined data

structures manipulate and share objectsThey cannot manipulate variables of primitive types.

They can manipulate objects of the type-wrapper classesBecause every class ultimately derives from Object.

Page 3: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Type-Wrapper Classes

Each of the numeric type-wrapper classes—Byte, Short, Integer, Long, Float and Double—extends class Number.

Also, the type-wrapper classes are final classes,you cannot extend them.

Primitive types do not have methods The methods related to a primitive type are

located in the corresponding type-wrapper class method parseInt is located in class IntegerparseInt converts a String to an int value

Page 4: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Autoboxing and Auto-Unboxing

Java provides boxing and unboxing conversions that automatically convert between primitive-type values and type-wrapper objects.

A boxing conversion converts a value of a primitive type to an object of the corresponding type-wrapper class.

An unboxing conversion converts an object of a type-wrapper class to a value of the corresponding primitive type.

These conversions are performed automaticallycalled autoboxing and auto-unboxing.

Page 5: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Autoboxing and Auto-UnboxingInteger[] integerArray = new Integer[5]; // create integerArrayintegerArray[0] = 10; // assign Integer 10 to integerArray[0]int value = integerArray[0]; // get int value of Integer

Autoboxing occurs when assigning an int value (10) to integerArray[0]integerArray stores references to Integer objects, not int values.

Auto-unboxing occurs when assigning integerArray[0] to int variable valuevariable value stores an int value, not a reference to an Integer

object. Boxing conversions occur in conditions to evaluate

primitive boolean values or Boolean objects.

Page 6: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Collections in JavaCollections in java is a framework

Framework provides an architecture to store and manipulate the group of objects.

All the operations on a data aresearching, sorting, insertion, manipulation, deletion etc.

These can be performed by Java Collections.

Java Collection simply means a single unit of objects.

Java Collection framework provides Many interfaces (Set, List, Queue, Deque etc.) Classes (ArrayList, Vector, LinkedList, PriorityQueue,

HashSet, LinkedHashSet, TreeSet etc).

Page 7: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Collections in Java

Question:What is Collection in java?Collection represents a single unit of objects

i.e. a group. Question: What is framework in java?Framrework provides readymade architecture.Framework represents set of classes and

interface.Framework is optional.

Page 8: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Collections in Java

Question: What is Collection framework?Collection framework represents a unified

architecture for storing and manipulating group of objects. It has nterfaces and its implementations i.e. classesIt has an algorithm

Page 9: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Hierarchy of Collection FrameworkThe java.util package contains all the classes and interfaces for Collection framework.

Page 10: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Iterator InterfaceIterator interface provides the facility of

iterating the elements in forward direction only.

Methods of Iterator interfaceThere are only three methods in the Iterator

interface. They are: public boolean hasNext() it returns true if iterator

has more elements.public object next() it returns the element and

moves the cursor pointer to the next element.public void remove() it removes the last elements

returned by the iterator. It is rarely used.

Page 11: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Interface CollectionInterface Collection contains bulk operations

Bulk operations performed on an entire collectionfor operations such as adding, clearing and comparing objects (or elements) in a collection.

A Collection can also be converted to an array. Interface Collection provides a method that returns an

Iterator objectIterator object allows a program to walk through the

collection and remove elements from it during the iteration. Other methods of interface Collection enable a

program to determine a collection’s size and whether a collection is empty.

Page 12: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Class Collections Class Collections provides static methods that search,

sort and perform other operations on collections. We cover Collections’ wrapper methods that enable you

to treat a collection as a synchronized collection or an unmodifiable collection

Synchronized collections are for use with multithreading , Multithreading enables programs to perform operations in

parallel. When two or more threads of a program share a collection,

problems might occur.Consider a traffic intersection.

If all cars were allowed to access the intersection at the same time, collisions might occur.

Page 13: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Class Collections We can synchronize access to a collection ensure

One thread manipulates the collection at a time. The synchronization wrapper methods of class

Collections return synchronized versions of collections that can be shared among threads in a program.

Unmodifiable collections are useful when clients of a class need to view a collection’s elements, They should not be allowed to modify the collection by

adding and removing elements.

Page 14: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

ListsA List is an ordered Collection that can contain

duplicate elements. List indices are zero based like array indicesThe methodsof the List are inherited from

CollectionList provides methods for manipulating

elements via their indices It manipulates a specified range of elements by

searching for elements It obtains a ListIterator to access the elements.

Page 15: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Lists Interface List is implemented by several classes

ArrayList, LinkedList , Vector. Autoboxing occurs when you add primitive-type values

to objects of these classesThe classes store only references to objects.

Classes ArrayList and Vector are resizable-array implementations of List.

Inserting an element between existing elements of an ArrayList or Vector is an inefficient operationAll elements after the new one must be moved out of the wayThis could be an expensive operation in a collection with a

large number of elements.

Page 16: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

A LinkedList enables efficient insertion (or removal) of elements in the middle of a collectionThis is much less efficient than an ArrayList for

jumping to a specific element in the collection.ArrayList and Vector have nearly identical

behaviors. Operations on Vectors are synchronized by

default, whereas those on ArrayLists are not.Class Vector is from Java 1.0, before the

collections framework was added to Java.

Lists

Page 17: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Lists Vector has some methods that are not part of interface List

and are not implemented in class ArrayList. For example, Vector methods addElement and add both

append an element to a Vector, but only method add is specified in interface List and implemented by ArrayList.

Unsynchronized collections provide better performance than synchronized ones.

For this reason, ArrayList is typically preferred over Vector in programs that do not share a collection among threads.

The Java collections API provides synchronization wrappers Synchronization wrappers can be used to add synchronization to

the unsynchronized collectionsSeveral powerful synchronized collections are available in the

Java concurrency APIs

Page 18: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Collections;public class Details { public static void main(String a[]){

List<String> syn = Collections.synchronizedList( new ArrayList<String>()); //Adding elements to synchronized ArrayList syn.add("one"); syn.add("two"); syn.add("three "); System.out.println("Iterating synchronized ArrayList:"); synchronized(syn) { Iterator<String> iterator = syn.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } }

Iterating synchronized ArrayList:onetwo three

Page 19: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

java.util.Collections.unmodifiableCollection() Method

The unmodifiableCollection() method is used to return an unmodifiable view of the specified collection.

An attempt to modify the collection will result in an UnsupportedOperationException.

Page 20: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

import java.util.*;public class CollectionsDemo { public static void main(String[] args) { // create array list List<Character> list = new ArrayList<Character>(); // add an element to the list list.add('X'); list.add('Y'); System.out.println("Initial list: "+ list); Collection<Character> tablelist = Collections.unmodifiableCollection(list); // try to modify the list tablelist.add('Z'); }}

Initial list: [X, Y] Exception in thread "main" java.lang.UnsupportedOperationException

Page 21: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

ArrayList and Iterator Example

The following program uses an ArrayList to demonstrate several capabilities of interface Collection.

The program places two Color arrays in ArrayLists and uses an Iterator to remove elements in the second ArrayList collection from the first.

Page 22: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Collection interface demonstrated via an ArrayList object.

// Collection interface demonstrated via an ArrayList object. import java.util.List; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionTest { public static void main(String[] args) { // add elements in colors array to list String[] colors = {"MAGENTA", "RED", "WHITE", "BLUE", "CYAN"};

List<String> list = new ArrayList<String>(); for (String color : colors)//populate list with Strings stored in array colors list.add(color); // adds color to end of list

Page 23: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

// add elements in removeColors array to removeList String[] removeColors = {"RED", "WHITE", "BLUE"};

List<String> removeList = new ArrayList<String>(); for (String color : removeColors)//populate removeList with Strings stored in array removeColors using List method add. removeList.add(color); // output list contents System.out.println("ArrayList: "); for (int count = 0; count < list.size(); count++)//calls List method size to get the number of elements in the ArrayList System.out.printf("%s ", list.get(count));//uses List method get to retrieve individual element values}

Page 24: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

// remove from list the colors contained in removeList removeColors(list, removeList);// output list contents System.out.printf("%n%nArrayList after calling removeColors:%n");

for (String color : list) System.out.printf("%s ", color);

Page 25: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

// remove colors specified in collection2 from collection1private static void removeColors(Collection<String> collection1, Collection<String> collection2) /* Method removeColors declares two Collection<String> parameters any two Collections containing Strings can be passed as arguments. The method accesses the elements of the first Collection (collection1) via an Iterator. */ { // get iterator Iterator<String> iterator = collection1.iterator();//Collection method iterator is called to get an Iterator for the Collection.//Interfaces Collection and Iterator are generic types.

Page 26: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

/*The loop-continuation condition calls Iterator method hasNext to determine whether there are more elements to iterate through. Method hasNext returns true if another element exists and false otherwise*/ while (iterator.hasNext()) // loop while collection has items

{ if (collection2.contains(iterator.next())) /*The if condition calls Iterator method next to obtain a reference to the next element and uses method contains of the second Collection to determine whether collection2 contains the element returned by next. If so, Iterator method is called to remove to remove the element from the Collection collection1.*/ iterator.remove(); // remove current element } } } // end class CollectionTest

Page 27: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Explanation We declare and initialize String arrays colors and

removeColors. We create ArrayList<String> objects We assign their references to List<String> variables list We removeList

ArrayList is a generic class, so we can specify a type argument (String) to indicate the type of the elements in each list.

You specify the type to store in a collection at compile time

Generic collections provide compile-time type safety that allows the compiler to catch attempts to use invalid types.You cannot store Employees in a collection of Strings.

Page 28: GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called

Type Inference with the <> Notation

List<String> list = new ArrayList<String>();and the line List<String> removeList = new ArrayList<String>();specify the type stored in the ArrayList (String) on the left and right sides of the initialization statements. Type inferencing with the <> notation in

statements that declare and create generic type variables and objects.