20、Java 泛型

1

Java

Java广~

1.1


使/

1.2  

package com.example.main;

/**
* @author lin
* @version 1.0
* @date 2020/7/12 21:31
* @Description TODO
*/
public class TestTypeMain {
   private static int add(int a, int b) {
       System.out.println(a + "+" + b + "=" + (a + b));
       return a + b;
  }

   private static float add(float a, float b) {
       System.out.println(a + "+" + b + "=" + (a + b));
       return a + b;
  }

   private static double add(double a, double b) {
       System.out.println(a + "+" + b + "=" + (a + b));
       return a + b;
  }

   private static <T extends Number> double add(T a, T b) {
       System.out.println(a + "+" + b + "=" + (a.doubleValue() + b.doubleValue()));
       return a.doubleValue() + b.doubleValue();
  }

   public static void main(String[] args) {
       System.out.println(TestTypeMain.add(1, 2));
       System.out.println(TestTypeMain.add(1f, 2f));
       System.out.println(TestTypeMain.add(1d, 2d));
       System.out.println(TestTypeMain.add(Integer.valueOf(1), Integer.valueOf(2)));
       System.out.println(TestTypeMain.add(Float.valueOf(1), Float.valueOf(2)));
       System.out.println(TestTypeMain.add(Double.valueOf(1), Double.valueOf(2)));
  }

}

   1+2=3
   3
   1.0+2.0=3.0
   3.0
   1.0+2.0=3.0
   3.0
   1+2=3.0
   3.0
   1.0+2.0=3.0
   3.0
   1.0+2.0=3.0
   3.0

1.3

1

2

2使

2.1

1public static < E > void printArray( E[] inputArray )

  public static <T extends Comparable<T>> T maximum(T x, T y, T z)

2public class Box<T> {  private T t; }

3public interface Generator<T> { public T next(); }

4List<String> list= new ArrayList<String>();

2.2

EElementjava
KKey
NNumber
TType
VValue

2.3

.


   /**
    * 
    * public<T>T
    * T.
    * 
    *   public <T,K> K showKeyName(Generic<T> container){
    *       ...
    *       }
    */
   public <T> T showKeyName(Generic<T> container){
       System.out.println("container key :" + container.getKey());
       //
       T test = container.getKey();
       return test;
  }

   //使Generic<Number>
   public void showKeyValue1(Generic<Number> obj){
       Log.d("","key value is " + obj.getKey());
  }

   //使?
   //?Number
   public void showKeyValue2(Generic<?> obj){
       Log.d("","key value is " + obj.getKey());
  }

    /**
    * "UnKnown class 'E' "
    * <T>,
    * TEE
   public <T> T showKeyName(Generic<E> container){
       ...
   }  
   */

   /**
    * "UnKnown class 'T' "
    * T
    * 
   public void showkey(T genericObj){

   }
   */

:

   /**
    * 
    * public<T>T
    * T.
    * 
    *   public <T,K> K showKeyName(Generic<T> container){
    *       ...
    *       }
    */
   public <T> T showKeyName(Generic<T> container){
       System.out.println("container key :" + container.getKey());
       //
       T test = container.getKey();
       return test;
  }

   //使Generic<Number>
   public void showKeyValue1(Generic<Number> obj){
       Log.d("","key value is " + obj.getKey());
  }

   //使?
   //?Number
   public void showKeyValue2(Generic<?> obj){
       Log.d("","key value is " + obj.getKey());
  }

    /**
    * "UnKnown class 'E' "
    * <T>,
    * TEE
   public <T> T showKeyName(Generic<E> container){
       ...
   }  
   */

   /**
    * "UnKnown class 'T' "
    * T
    * 
   public void showkey(T genericObj){

   }
   */

2.4

public class GenericClass{}

package com.example.main;

/**
* @author lin
* @version 1.0
* @date 2020/7/12 21:49
* @Description 
*/
public class GenericClass<T> {
   private T data;

   public T getData() {
       return data;
  }

   public void setData(T data) {
       this.data = data;
  }

   public static void main(String[] args) {
       GenericClass<String> genericClass = new GenericClass<>();
       genericClass.setData("Generic Class");
       System.out.println(genericClass.getData());
  }
}

2.5

public interface GenericIntercace{}

package com.example.main;

/**
* @author lin
* @version 1.0
* @date 2020/7/12 21:50
* @Description TODO
*/
public interface GenericInterface<T> {
  public T getData();
}

public class ImplGenericInterface1 implements GenericIntercace

package com.example.main;

/**
* @author lin
* @version 1.0
* @date 2020/7/12 21:53
* @Description TODO
*/
public class ImplGenericInterface1<T> implements GenericInterface<T> {
   private T data;

   private void setData(T data) {
       this.data = data;
  }

   @Override
   public T getData() {
       return this.data;
  }

   public static void main(String[] args) {
       ImplGenericInterface1<String> implGenericInterface1 = new ImplGenericInterface1<>();
       implGenericInterface1.setData("Generic Interface1");
       System.out.println(implGenericInterface1.getData());
  }
}

:

public class ImplGenericInterface2 implements GenericIntercace<String> {}

package com.example.main;

/**
* @author lin
* @version 1.0
* @date 2020/7/12 21:55
* @Description TODO
*/
public class ImplGenericInterface2 implements GenericInterface<String> {
   @Override
   public String getData() {
       return "hello world ";
  }

   public static void main(String[] args) {
       ImplGenericInterface2 implGenericInterface2 = new ImplGenericInterface2();
       System.out.println(implGenericInterface2.getData());
  }
}

2.6

<? extends T> <? super T> <?>? extends TTT

? super TTT

?

TEKV

西 T A-Z T TEKV

2.6.1 java

static int countLegs (List<? extends Animal > animals ) {
   int retVal = 0;
   for ( Animal animal : animals )
  {
       retVal += animal.countLegs();
  }
   return retVal;
}

static int countLegs1 (List< Animal > animals ){
   int retVal = 0;
   for ( Animal animal : animals )
  {
       retVal += animal.countLegs();
  }
   return retVal;
}

2.6.2T (type) java

: super Object

使 super  E  E 

private <T> void test(List<? super T> dst, List<T> src){
   for (T t : src) {
       dst.add(t);
  }
}

public static void main(String[] args) {
   List<Dog> dogs = new ArrayList<>();
   List<Animal> animals = new ArrayList<>();
   new Test3().test(animals,dogs);
}

class gent<T> {
   public void test() {
       System.out.println("gent");
  }
}

class supC {
   public String toString() {
       return "supA";
  }
}

public class Bc extends supC {
   String b;

   public Bc( String b ) {
       this.b = b;
  }

   public String toString() {
       return "subB";
  }

   // supC
   public void test( gent<? extends supC> o ) {
       System.out.println("Bc");
  }

   public static void main( String[] args ) {
       Bc bc = new Bc("test");
       gent<Bc> oGent = new gent<Bc>();
       bc.test(oGent);    // oGent supC
  }
}

3

3.1

使访

使

public class StaticGenerator<T> {
  ....
  ....
   /**
    * 使
    * 使使
    * public static void show(T t){..},
         "StaticGenerator cannot be refrenced from static context"
    */
   public static <T> void show(T t){

  }
}

3.2

1, 2,: public class ArrayList<E> extends AbstractList<E> 3,使

/**
* Authorlin 2020/7/12 21:55
* <p>
* Description: 
*/
public class GenericInherit<T> {
   private T data1;
   private T data2;

   public T getData1() {
       return data1;
  }

   public void setData1(T data1) {
       this.data1 = data1;
  }

   public T getData2() {
       return data2;
  }

   public void setData2(T data2) {
       this.data2 = data2;
  }

   public static <V> void setData2(GenericInherit<Father> data2) {

  }

   public static void main(String[] args) {
//       Son  Father
       Father father = new Father();
       Son son = new Son();
       GenericInherit<Father> fatherGenericInherit = new GenericInherit<>();
       GenericInherit<Son> sonGenericInherit = new GenericInherit<>();
       SubGenericInherit<Father> fatherSubGenericInherit = new SubGenericInherit<>();
       SubGenericInherit<Son> sonSubGenericInherit = new SubGenericInherit<>();

       /**
        * 
        * GenericInherit<Father> GenericInherit<Son> 
        * Incompatible types.
        */
       father = new Son();
//       fatherGenericInherit=new GenericInherit<Son>();

       /**
        * : public class ArrayList<E> extends AbstractList<E>
        */
       fatherGenericInherit=new SubGenericInherit<Father>();

       /**
        *使
        */
       setData2(fatherGenericInherit);
//       setData2(sonGenericInherit);
       setData2(fatherSubGenericInherit);
//       setData2(sonSubGenericInherit);

  }

   private static class SubGenericInherit<T> extends GenericInherit<T> {

  }

3.3

JavaJava1.5JavaC++Java JavaObject.

GenericClass<String> stringGenericClass=new GenericClass<>();
GenericClass<Integer> integerGenericClass=new GenericClass<>();

C++GenericClass<String>GenericClass<Integer> JavaGenericClass<Object>

/**
* Authorlin 2020/7/12 21:55
* <p>
* Description:
*/
public class GenericTheory {
   public static void main(String[] args) {
       Map<String, String> map = new HashMap<>();
       map.put("Key", "Value");
       System.out.println(map.get("Key"));
       GenericClass<String, String> genericClass = new GenericClass<>();
       genericClass.put("Key", "Value");
       System.out.println(genericClass.get("Key"));
  }

   public static class GenericClass<K, V> {
       private K key;
       private V value;

       public void put(K key, V value) {
           this.key = key;
           this.value = value;
      }

       public V get(V key) {
           return value;
      }
  }

   /**
    * GenericClass2<Object>
    * @param <T>
    */
   private class GenericClass2<T> {

  }

   /**
    * GenericClass3<ArrayList>
    * 使SerializableSerializable
    * @param <T>
    */
   private class GenericClass3<T extends ArrayList & Serializable> {

  }
}

public static void main(String[] args) {
       Map<String, String> map = new HashMap();
       map.put("Key", "Value");
       System.out.println((String)map.get("Key"));
       GenericTheory.GenericClass<String, String> genericClass = new GenericTheory.GenericClass();
       genericClass.put("Key", "Value");
       System.out.println((String)genericClass.get("Key"));
  }

4.

1JSON

apijson

{
   "code":200,
   "msg":"",
   "data":{
       "name":"Lin",
       "email":"10086"
  }
}
BaseResponse .java
/**
* Authorlin 2020/7/12 21:55
* <p>
* Description: 
*/
public class BaseResponse {

   private int code;
   private String msg;

   public int getCode() {
       return code;
  }

   public void setCode(int code) {
       this.code = code;
  }

   public String getMsg() {
       return msg;
  }

   public void setMsg(String msg) {
       this.msg = msg;
  }
}
UserResponse.java
/**
* Authorlin 2020/7/12 21:55
* <p>
* Description: 
*/
public class UserResponse<T> extends BaseResponse {
   private T data;

   public T getData() {
       return data;
  }

   public void setData(T data) {
       this.data = data;
  }
}

2+

/**
* Authorlin 2020/7/12 21:55
* <p>
* Description: 
*/
public class GenericUtils {

   public static class Movie {
       private String name;
       private Date time;

       public String getName() {
           return name;
      }

       public Date getTime() {
           return time;
      }

       public Movie(String name, Date time) {
           this.name = name;
           this.time = time;
      }

       @Override
       public String toString() {
           return "Movie{" + "name='" + name + ''' + ", time=" + time + '}';
      }
  }

   public static void main(String[] args) {
       List<Movie> movieList = new ArrayList<>();
       for (int i = 0; i < 5; i++) {
           movieList.add(new Movie("movie" + i, new Date()));
      }
       System.out.println(":" + movieList.toString());

       GenericUtils.sortAnyList(movieList, "name", true);
       System.out.println("name" + movieList.toString());

       GenericUtils.sortAnyList(movieList, "name", false);
       System.out.println("name" + movieList.toString());
  }

   /**
    * 
    * @param targetList List
    * @param sortField 
    * @param sortMode   truefalse
    */
   public static <T> void sortAnyList(List<T> targetList, final String sortField, final boolean sortMode) {
       if (targetList == null || targetList.size() < 2 || sortField == null || sortField.length() == 0) {
           return;
      }
       Collections.sort(targetList, new Comparator<Object>() {
           @Override
           public int compare(Object obj1, Object obj2) {
               int retVal = 0;
               try {
                   // getXxx()
                   String methodStr = "get" + sortField.substring(0, 1).toUpperCase() + sortField.substring(1);
                   Method method1 = ((T) obj1).getClass().getMethod(methodStr, null);
                   Method method2 = ((T) obj2).getClass().getMethod(methodStr, null);
                   if (sortMode) {
                       retVal = method1.invoke(((T) obj1), null).toString().compareTo(method2.invoke(((T) obj2), null).toString());
                  } else {
                       retVal = method2.invoke(((T) obj2), null).toString().compareTo(method1.invoke(((T) obj1), null).toString());
                  }
              } catch (Exception e) {
                   System.out.println("List<" + ((T) obj1).getClass().getName() + ">");
                   e.printStackTrace();
              }
               return retVal;
          }
      });
  }
}

3Gson使-TypeToken

/**
* AuthorJay On 2019/5/11 22:11
* <p>
* Description: Gson使
*/
public class GsonGeneric {
   public static class Person {
       private String name;
       private int age;

       public Person(String name, int age) {
           this.name = name;
           this.age = age;
      }

       @Override
       public String toString() {
           return "Person{" +
                   "name='" + name + ''' +
                   ", age=" + age +
                   '}';
      }
  }

   public static void main(String[] args) {
       Gson gson = new Gson();
       List<Person> personList = new ArrayList<>();
       for (int i = 0; i < 5; i++) {
           personList.add(new Person("name" + i, 18 + i));
      }
       // Serialization
       String json = gson.toJson(personList);
       System.out.println(json);
       // Deserialization
       Type personType = new TypeToken<List<Person>>() {}.getType();
       List<Person> personList2 = gson.fromJson(json, personType);
       System.out.println(personList2);
  }
}


                

圈~

 注公众号

原文地址:https://www.cnblogs.com/naimao/p/13353354.html