Your SlideShare is downloading. ×
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Applying Generics
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Applying Generics

1,059

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,059
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Applying Generics Writing Type-Safe Code
  • 2. Generic Class or Interface
    • In Java, an Interface or a Class can be declared as taking one or more type parameters. If this is the case, the respective class or the interface is said to be generic.
    • Type Parameters are written in angle brackets. It serves a place holder for type arguments.
    • Each type parameter is replaced by a type argument when we create an object of the generic type.
    class X<T1,T2> { private T1 ref1; private T2 ref2; public X(T1 ref1,T2 ref2) { this.ref1 = ref1; this.ref2 = ref2; } public T1 getRef1() { return ref1; } public T2 getRef2() { return ref2; } }
  • 3. Primary purpose of Java generics
    • While implementing & using Collections framework, We often require to specify that a collection contains elements of a certain type. i.e., homogenous elements
    • such as a list of integral values
    • a list of strings.
    • Is this feasible or desirable to create separate Implementation classes for holding homogenous collections like IntegerList, StringList, FloatList etc?
    • Isn’t it good to have a single implementation of the collection class and use it to hold elements of different types?
    • implementation of one generic class that can be instantiated for a variety of types.
  • 4. Prime Benefit
    • Early error detection at compile time. Thus, helps making our code Type Safe.
    • It better to get Compile-time errors rather than getting Exceptions at Runtime exceptions.
    • In Java, a program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastExceptions at runtime.
    What’s the meaning of Type-safety?
  • 5. SubTyping & WildCards
    • Objective :
    • How subtyping works.
    • How wildcards let us use subtyping in connection with generics.
  • 6. Subtyping and the Substitution Principle
    • As we know one type is a subtype of another if they are related by an extends or implements clause.
        • Integer is a subtype of Number
        • ArrayList<E> is a subtype of List<E>
        • List<E> is a subtype of Collection<E>
    • Subtyping is transitive, meaning that if one type is a subtype of a second, and the second is a subtype of a third, then the first is a subtype of the third.
    • Substitution Principle : Wherever a value of one type is expected, we may provide a value of any subtype of that type.
        • List<Number> list = new ArrayList<Number>();
        • List.add(4);
        • List.add(6.7);
  • 7. Substitution Principle contd.
    • Integer is a subtype of Number.
    • Is List<Integer> a subtype of List<Number>?
      • List<Integer> ints = new ArrayList<Integer>();
      • ints.add(5);
      • ints.add(56);
      • List<Number> nums = ints; // is this allowed?
      • nums.add(3.14);
      • Is substitution principle being applied here?
      • Think of Reverse : Is List<Number> a subtype of List<Integer>
      • ArrayList<Number> nums = new ArrayList<Number>();
      • nums.add(8); nums.add(6.7); nums.add(9.89f);
      • ArrayList<Integer> ints = nums; // ?
  • 8. Substitution Principle contd.
    • Conclusion : ArrayList<Integer> isn’t a subtype of ArrayList<Number> even if Integer is a subtype of Number.
    • Behavior of Arrays : We know
          • Integer[] is a subtype of Number[].
  • 9. Bounded Type Parameter
    • class GenTest<T extends Number>
    • {
    • T[] nums;
    • GenTest(T[] arr)
    • { nums = arr; }
    • void sum()
    • {
    • double sum=0.0;
    • for(T v:nums)
    • sum+=v.doubleValue();
    • System.out.println(&quot;Sum : &quot;+sum);
    • }
    • }
    public static void main(String[] args) { Integer ints[] = {7,8,5}; Double d[] = {5.3,7.44,6.008}; Float f[] = {4.3f,1.2f,2.3f}; GenTest<Integer> ref1 = new GenTest<Integer>(ints); GenTest<Double> ref2 = new GenTest<Double>(d); GenTest<Float> ref3 = new GenTest<Float>(f); ref1.sum(); ref2.sum(); ref3.sum(); }
  • 10. WildCard (?)
    • Purpose :
    • Sometimes It’s desirable to have lists to behave more like arrays, in that we want to accept not only a list with elements of a given type, but also a list with elements of any subtype of a given type.
    • Types : 2
        • Wildcard with extends ? extends E
        • Wildcard with super ? super E
  • 11. Using ? extends T
    • Think of the following:
        • interface Collection<E> {
        • ...
        • public boolean addAll(Collection<? extends E> c);
        • ...
        • }
    • Situation :
    • We’ve a list of integers and we want to add this list in the list of floats.
        • OR We want to add all of the members of one collection to another collection:
    • Possibilities : 2
        • It’s OK to add all elements of a collection whose type is E.
        • It’s also OK to all elements of a collection which are subtypes of E.
  • 12. Using ? extends T contd.
    • ArrayList<Number> nums = new ArrayList<Number>();
    • ArrayList<Integer> ints = new ArrayList<Integer>();
    • ints.add(4); ints.add(60); ints.add(45);
    • ArrayList<Double> dbls = new ArrayList<Double>();
    • dbls.add(3.4); dbls.add(5.22); dbls.add(12.33);
    • nums.addAll(ints);
    • nums.addAll(dbls);
    • Points to understand :
    • ArrayList<Integer> is a subType of ArrayList<? extends Number>.
    • ArrayList<Double> is a subType of ArrayList<? extends Number>.
  • 13. Using ? extends T contd.
    • ArrayList<Integer> ints = new ArrayList<Integer>();
    • ints.add(45);
    • ints.add(0);
    • ints.add(786);
    • ArrayList<? Extends Number> nums = ints; // is this OK?
    • nums.add(4.5); // is this OK?
    • Points to Understand :
    • ArrayList<Number> isn’t a supertype of ArrayList<Integer> but
    • ArrayList<? extends Number> is a supertype of ArrayList<Integer>
    Always Remember if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure.
  • 14. ? super T
    • Situation :
    • We want to copy all elements from a List into another List.
    • Think of the following :
    • void copy(List<? super T> dst, List<? extends T> src)
    • {
    • for (int i = 0; i < src.size(); i++)
    • {
    • dst.set(i, src.get(i));
    • }
    • }
    • ? super T means that the destination list may have elements of any type that is a supertype of T.
  • 15. ? super T contd.
    • Think of the following :
    • void copy(List<T> dst, List<T> src)
    • void copy(List<T> dst, List<? extends T> src)
    • void copy(List<? super T> dst, List<T> src)
    • void copy(List<? super T> dst, List<? extends T> src)
    • Conclusion :
    • Always use wildcards in a signature if possible, since this permits the widest range of calls.
  • 16. Get & Put Principle
    • Where to use ? extends T ?
    • Where to use ? super T?
    • Where we shouldn’t use wildcard at all?
    • Use an extends wildcard when only getting values out of a structure is needed.
    • Use a super wildcard when only putting values into a structure is needed.
    • Don't use a wildcard when both get and put are required.
  • 17. Are the following code snippets correct?
    • ArrayList<Integer> i;
    • i = new ArrayList<Integer>();
    • i.add(6);
    • i.add(89);
    • ArrayList<? extends Integer> al = i;
    ArrayList<Number> i; i = new ArrayList<Number>(); i.add(6.7); i.add(89); ArrayList<? super Integer> al = i; Test your understanding Is ArrayList<String> and ArrayList<? extends String> same?
  • 18. Comparison of Arrays & Lists
    • Array subtyping is covariant, meaning that type S[] is considered to be a subtype of T[] whenever S is a subtype of T.
    • Integer ints[] = new Integer[]{1,2,4,52};
      • Number[] nums = ints;
      • nums[0]=4.5;
      • The subtyping relation for generics is invariant, meaning that type List<S> is not considered to be a subtype of List<T>.
      • List<Integer> ints = new ArrayList<Integer>();
      • ints.add(7); ints.add(67);
      • List<Number> nums = ints;
      • nums.put(2, 3.14);
      • How can we add covariant nature to generics?
  • 19. Comparison & Bounds
    • java.lang.Comparable<T>
    • public int compareTo(T o);
    • An object belonging to a class can only be compared with an object belonging to the same class. For instance, Integer implements Comparable<Integer>:
    • Integer a=0,b=1;
    • a.compareTo(b); // returns -1
    • String s1 =“yahoo”;
    • String s2 = “google”;
    • s1.compareTo(s2); // returns a +ve value
  • 20. Maximum of a Collection
    • public static <T extends Comparable<T>> T max(Collection<T> coll)
    • {
    • T candidate = coll.iterator().next();
    • for (T elt : coll) {
    • if (candidate.compareTo(elt) < 0) candidate = elt;
    • }
    • return candidate;
    • }
    • Here max can return any type T such that T is a subtype of Comparable<T>. i.e., T is bounded by Comparable<T>.
    • List<Integer> ints = Arrays.asList(0,1,2);
    • List<String> strs = Arrays.asList(&quot;zero&quot;,&quot;one&quot;,&quot;two&quot;);
    • Is the following code legal?
    • List<Number> nums = Arrays.asList(0,1,2,3.14);
    • Number n = Collections.max(nums) == 3,14;
  • 21. Comparison
    • Array
  • 22. sts
    • Array subtyping is covariant, meaning that type S[] is considered to be a subtype
  • 23.  

×