Java Generic Type Inference

Introduction

The declaration syntax for a generic reference and instance creation has this general form:

class-name<type-arg-list > var-name = new  class-name <>(cons-arg-list);

Here, the type argument list of the constructor in the new clause is empty.                             
class MyClass<T, V> {
  T ob1;/* www .  ja  v a2s  .com*/
  V ob2;

  MyClass(T o1, V o2) {
    ob1 = o1;
    ob2 = o2;
  }
}

// Demonstrate generic method override.
public class Main {
  public static void main(String args[]) {

    MyClass<Integer, String> mcOb = new MyClass<Integer, String>(98, "A String");

    MyClass<Integer, String> mcOb2 = new MyClass<>(98, "A String");
    
  }
}

Type inference can be applied to parameter passing.

For example,

boolean isSame(MyClass<T, V> o) {  
   if(ob1 == o.ob1 && ob2 == o.ob2) 
      return true;  
   else 
      return false;  
}    

the following call is legal:

if(mcOb.isSame(new MyClass<>(1, "test"))) 
   System.out.println("Same"); 
class MyClass<T, V> {
  T ob1;/*from   www . j  a  va  2s. c  o  m*/
  V ob2;

  MyClass(T o1, V o2) {
    ob1 = o1;
    ob2 = o2;
  }

  boolean isSame(MyClass<T, V> o) {
    if (ob1 == o.ob1 && ob2 == o.ob2)
      return true;
    else
      return false;
  }

  }

// Demonstrate generic method override.
public class Main {

  public static void main(String args[]) {

    MyClass<Integer, String> mcOb = new MyClass<Integer, String>(98, "A String");

    MyClass<Integer, String> mcOb2 = new MyClass<>(98, "A String");
    if (mcOb.isSame(new MyClass<>(1, "test"))) {
      System.out.println("Same");
    } else {
      System.out.println("not Same");
    }
  }
}



PreviousNext

Related