1 / 65

Chapter 21 Generics

Chapter 21 Generics. Why Do You Get a Warning?. public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); list.add("Java Programming"); } }.

marja
Download Presentation

Chapter 21 Generics

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 21 Generics

  2. Why Do You Get a Warning? public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); list.add("Java Programming"); } } To understand the compile warning on this line, you need to learn JDK 1.5 generics.

  3. Fix the Warning public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList<String> list = new java.util.ArrayList<String>(); list.add("Java Programming"); } } ` No compile warning on this line.

  4. What is Generics? • Generics is the capability to parameterize types. With this capability, you can define a class or a method with generic types that can be substituted using concrete types by the compiler. For example, you may define a generic stack class that stores the elements of a generic type. From this generic class, you may create a stack object for holding strings and a stack object for holding numbers. Here, strings and numbers are concrete types that replace the generic type.

  5. Why Generics? • The key benefit of generics is to enable errors to be detected at compile time rather than at runtime. A generic class or method permits you to specify allowable types of objects that the class or method may work with. If you attempt to use the class or method with an incompatible object, the compile error occurs.

  6. Generic Type Generic Instantiation Runtime error Improves reliability Compile error

  7. Generic ArrayList in JDK 1.5

  8. No Casting Needed ArrayList<Double> list = new ArrayList<Double>(); list.add(5.5); // 5.5 is automatically converted to new Double(5.5) list.add(3.0); // 3.0 is automatically converted to new Double(3.0) Double doubleObject = list.get(0); // No casting is needed double d = list.get(1); // Automatically converted to double

  9. Declaring Generic Classes and Interfaces GenericStack

  10. Generic Methods public static <E> void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } public static void print(Object[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

  11. Bounded Generic Type public static void main(String[] args ) { Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println("Same area? " + equalArea(rectangle, circle)); } public static <E extends GeometricObject> boolean equalArea(E object1, E object2) { return object1.getArea() == object2.getArea(); }

  12. Raw Type and Backward Compatibility // raw type ArrayList list = new ArrayList(); This is roughly equivalent to ArrayList<Object> list = new ArrayList<Object>();

  13. Raw Type is Unsafe // Max.java: Find a maximum object public class Max { /** Return the maximum between two objects */ public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } } Max.max("Welcome", 23); Runtime Error:

  14. Make it Safe // Max1.java: Find a maximum object public class Max1 { /** Return the maximum between two objects */ public static <E extends Comparable<E>> E max(E o1, E o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } } Max.max("Welcome", 23);

  15. Wildcards Why wildcards are necessary? See this example. WildCardDemo1 ? unbounded wildcard ? extends T bounded wildcard ? super T lower bound wildcard WildCardDemo2 WildCardDemo3

  16. Generic Types and Wildcard Types

  17. Avoiding Unsafe Raw Types Use new ArrayList<ConcreteType>() Instead of new ArrayList(); Run TestArrayListNew

  18. Erasure and Restrictions on Generics Generics are implemented using an approach called type erasure. The compiler uses the generic type information to compile the code, but erases it afterwards. So the generic information is not available at run time. This approach enables the generic code to be backward-compatible with the legacy code that uses raw types.

  19. Compile Time Checking For example, the compiler checks whether generics is used correctly for the following code in (a) and translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.

  20. Important Facts It is important to note that a generic class is shared by all its instances regardless of its actual generic type. GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Integer> stack2 = new GenericStack<Integer>(); Although GenericStack<String> and GenericStack<Integer> are two types, but there is only one class GenericStack loaded into the JVM.

  21. Restrictions on Generics • Restriction 1: Cannot Create an Instance of a Generic Type. (i.e., new E()). • Restriction 2: Generic Array Creation is Not Allowed. (i.e., new E[100]). • Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. • Restriction 4: Exception Classes Cannot be Generic.

  22. Chapter 22 Java Collections Framework

  23. Java Collection Framework hierarchy A collection is a container object that represents a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named sets, lists, and maps.

  24. Java Collection Framework hierarchy, cont. Set and List are subinterfaces of Collection.

  25. Java Collection Framework hierarchy, cont. An instance of Map represents a group of objects, each of which is associated with a key. You can get the object from a map using a key, and you have to use a key to put the object into the map.

  26. The Collection Interface The Collection interface is the root interface for manipulating a collection of objects.

  27. The Set Interface The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.

  28. The Set Interface Hierarchy

  29. The AbstractSet Class The AbstractSet class is a convenience class that extends AbstractCollection and implements Set. The AbstractSet class provides concrete implementations for the equals method and the hashCode method. The hash code of a set is the sum of the hash code of all the elements in the set. Since the size method and iterator method are not implemented in the AbstractSet class, AbstractSet is an abstract class.

  30. The HashSet Class The HashSet class is a concrete class that implements Set. It can be used to store duplicate-free elements. For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code.

  31. Example: Using HashSet and Iterator This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list. TestHashSet Run

  32. JDK 1.5 Feature TIP: for-each loop You can simplify the code in Lines 21-26 using a JDK 1.5 enhanced for loop without using an iterator, as follows: for (Object element: set) System.out.print(element.toString() + " ");

  33. Example: Using LinkedHashSet This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list. TestLinkedHashSet Run

  34. The SortedSet Interface and the TreeSet Class SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order. The elements can be sorted in two ways.

  35. The SortedSet Interface and the TreeSet Class, cont. One way is to use the Comparable interface. The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you don’t want to use the compareTo method in the class that implements the Comparable interface. This approach is referred to as order by comparator.

  36. Example: Using TreeSet to Sort Elements in a Set This example creates a hash set filled with strings, and then creates a tree set for the same strings. The strings are sorted in the tree set using the compareTo method in the Comparable interface. The example also creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. TestTreeSet Run

  37. The Comparator Interface Sometimes you want to insert elements of different types into a tree set. The elements may not be instances of Comparable or are not comparable. You can define a comparator to compare these elements. To do so, create a class that implements the java.util.Comparator interface. The Comparator interface has two methods, compare and equals.

  38. The Comparator Interface public int compare(Object element1, Object element2) Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal. public boolean equals(Object element) Returns true if the specified object is also a comparator and imposes the same ordering as this comparator. GeometricObjectComparator

  39. Example: The Using Comparator to Sort Elements in a Set Write a program that demonstrates how to sort elements in a tree set using the Comparator interface. The example creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. TestTreeSetWithComparator Run

  40. The List Interface A set stores non-duplicate elements. To allow duplicate elements to be stored in a collection, you need to use a list. A list can not only store duplicate elements, but can also allow the user to specify where the element is stored. The user can access the element by index.

  41. The List Interface, cont.

  42. The List Iterator

  43. ArrayList and LinkedList The ArrayList class and the LinkedList class are concrete implementations of the List interface. Which of the two classes you use depends on your specific needs. If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements from any place in the list, you should choose LinkedList. A list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.

  44. java.util.ArrayList

  45. java.util.LinkedList

  46. Example: Using ArrayList and LinkedList This example creates an array list filled with numbers, and inserts new elements into the specified location in the list. The example also creates a linked list from the array list, inserts and removes the elements from the list. Finally, the example traverses the list forward and backward. TestList Run

  47. The Collections Class The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read-only collection classes.

  48. The Collections Class UML Diagram

  49. Example: Using the Collections Class This example demonstrates using the methods in the Collections class. The example creates a list, sorts it, and searches for an element. The example wraps the list into a synchronized and read-only list. TestCollections Run

  50. The Vector and Stack Classes The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them are the Vector class and the Stack class. These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility.

More Related