Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called."— Presentation transcript:

1 GENERIC COLLECTIONS

2 Type-Wrapper Classes  Each 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. primitive-type values as objects.  These enable you to manipulate primitive-type values as objects.  This is important because Java’s predefined data structures manipulate and share objects variables of primitive types  They cannot manipulate variables of primitive types. objects of the type-wrapper classes  They can manipulate objects of the type-wrapper classes  Because every class ultimately derives from Object.

3 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. not have methods  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 Integer parseInt converts a String to an int value

4 Autoboxing and Auto-Unboxing between primitive- type values and type-wrapper objects  Java provides boxing and unboxing conversions that automatically convert between primitive- type values and type-wrapper objects. converts a value of a  A boxing conversion converts a value of a primitive type to an object of the corresponding type-wrapper class. converts an object to a value primitive type  An unboxing conversion converts an object of a type-wrapper class to a value of the corresponding primitive type.  These conversions are performed automatically  called autoboxing and auto-unboxing.

5 Autoboxing and Auto-Unboxing Integer[] integerArray = new Integer[5]; // create integerArray integerArray[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] Integer objects  integerArray stores references to Integer objects, not int values.  Auto-unboxing occurs when assigning integerArray[0] to int variable value  variable value stores an int value, not a reference to an Integer object. primitive boolean values Boolean objects  Boxing conversions occur in conditions to evaluate primitive boolean values or Boolean objects.

6 Collections in Java  Collections in java is a framework  Framework provides an architecture to store and manipulate the group of objects.  All the operations on a data are  searching, 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).

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

8 Collections in Java Question: What is Collection framework? storing  Collection framework represents a unified architecture for storing and manipulating group of objects. It has nterfaces and its implementations i.e. classes  It has an algorithm

9 Hierarchy of Collection Framework The java.util package contains all the classes and interfaces for Collection framework.

10 Iterator Interface  Iterator interface provides the facility of iterating the elements in forward direction only. Methods of Iterator interface  There 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.

11 Interface Collection  Interface Collection contains bulk operations  Bulk operations performed on an entire collection for 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 object  Iterator 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.

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

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

14 Lists  A List is an ordered Collection that can contain duplicate elements.  List indices are zero based like array indices  The methodsof the List are inherited from Collection  List 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.

15 Lists  Interface List is implemented by several classes  ArrayList, LinkedList, Vector.  Autoboxing occurs when you add primitive-type values to objects of these classes  The 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 operation  All elements after the new one must be moved out of the way  This could be an expensive operation in a collection with a large number of elements.

16  A LinkedList enables efficient insertion (or removal) of elements in the middle of a collection  This 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

17  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 collections  Several powerful synchronized collections are available in the Java concurrency APIs

18 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 syn = Collections.synchronizedList( new ArrayList ()); //Adding elements to synchronized ArrayList syn.add("one"); syn.add("two"); syn.add("three "); System.out.println("Iterating synchronized ArrayList:"); synchronized(syn) { Iterator iterator = syn.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } } Iterating synchronized ArrayList: one two three

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

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

21 ArrayList and Iterator Example  The following program uses an ArrayList to demonstrate several capabilities of interface Collection. remove elements in the second ArrayList collection from the first.  The program places two Color arrays in ArrayLists and uses an Iterator to remove elements in the second ArrayList collection from the first.

22 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 list = new ArrayList (); for (String color : colors) //populate list with Strings stored in array colors list.add(color); // adds color to end of list

23 // add elements in removeColors array to removeList String[] removeColors = {"RED", "WHITE", "BLUE"}; List removeList = new ArrayList (); 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 }

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

25 // remove colors specified in collection2 from collection1 private static void removeColors(Collection collection1, Collection collection2) /* Method removeColors declares two Collection 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 iterator = collection1.iterator(); //Collection method iterator is called to get an Iterator for the Collection. //Interfaces Collection and Iterator are generic types.

26 /*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

27 Explanation  We declare and initialize String arrays colors and removeColors.  We create ArrayList objects  We assign their references to List 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.

28 Type Inference with the <> Notation List list = new ArrayList (); and the line List removeList = new ArrayList (); specify the type stored in the ArrayList (String) on the left and right sides of the initialization statements. variables and objects.  Type inferencing with the <> notation in statements that declare and create generic type variables and objects.


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

Similar presentations


Ads by Google