Java 泛型理解(一)

来源:互联网 发布:cuda linux 编辑:程序博客网 时间:2024/04/29 18:30

Java 泛型理解(一)


Java 泛型中的标记符含义

  • E - Element (在集合中使用,因为集合中存放的是元素)
  • T - Type(Java 类)
  • K - Key(键)
  • V - Value(值)
  • N - Number(数值类型)
  • ? - 表示不确定的java类型
  • S、U、V - 2nd、3rd、4th types

注意

  1. 用泛型只是确定了集合内的元素的类型,但却是在编译时确定了元素的类型再取出来时已经不再需要强转,增强程序可读性,稳定性和效率
  2. 不用泛型时,如果是装入集合操作,那么元素都被当做Object对待,失去自己的类型,那么从集合中取出来时,往往需要转型,效率低,容易产生错误
  3. 泛型的标记符只相当于占位符的作用

Java 泛型使用

  • 泛型类
  • 泛型接口
  • 泛型方法

在不知道传入什么类型的参数的时候,我们大多数都可以使用泛型来解决。

自定义泛型类


public class Genericity<K, V> {    private K key;    private V value;    public Genericity(K key, V value){        this.key = key;        this.value = value;    }    public K getKey(){        return key;    }    public void setKey(K key){        this.key = key;    }    public V getValue() {        return value;    }}

在自定义泛型类的格式如上面所示,在需要泛化的类上Genericity

自定义泛型接口


先定义一个泛化接口:

public interface GenericityInterface<T> {    public T go2Write(T type);}

让上面已经泛化的自定义类Genericity,实现上面的泛型接口:

public class Genericity<K, V, T> implements GenericityInterface<T>{    private K key;    private V value;    public Genericity(K key, V value){        this.key = key;        this.value = value;    }    public K getKey(){        return key;    }    public void setKey(K key){        this.key = key;    }    public V getValue() {        return value;    }    @Override    public T go2Write(T type) {        return null;    }}

自定义泛型方法


/*** 传入Genericity泛型参数,泛型类的参数前后调用可以传入相同的指     定的类型***/private static <K, V, T> void testGenericity1(Genericity<K, V, T> genericity){    System.out.println("key1 = " + genericity.getKey()+", value1 = "+genericity.getValue());}/*** 传入Genericity泛型参数,但泛型类的参数是'?'通配符,前后调用可以传入不同的指定的类型***/private static void testGenericity2(Genericity<?, ?,?> genericity){    System.out.println("key2 = " + genericity.getKey()+", value2 = "+genericity.getValue());}/*** 传入多个泛型参数* 而且泛型可以是多个不同的类**/private static <T> void testGenericity3(T... args){    for(T arg:args){        System.out.println("arg = " + arg);    }}

使用泛型方法

public static void main(String[] args) {    // 指定<K,V>的类型为<String, Integer,String>    Genericity<String, Integer,String> genericity1 = new Genericity<String, Integer,String>("age", 1);    // 传入<K,V>的类型为<String, Integer,String>,后面不能再传入其他类型    testGenericity1(genericity1);    // 指定<K,V>的类型为<String, String,String>    Genericity<String, String,String> genericity2 = new Genericity<String,String,String>("age", "12");    testGenericity2(genericity1); // 传入<K,V>的类型为<String, Integer>    testGenericity2(genericity2); // 传入<K,V>的类型为<String, String>    testGenericity3("age", 123, 11.11, true);}

输出结果:

key = age, value = 1key2 = age, value2 = 1key2 = age, value2 = 12arg = agearg = 123arg = 11.11arg = true

个人简单使用泛型的记录。很久很久没写博客了,重新拾起,希望自己能坚持写,把自己技术提升上去,也把博客质量提升上去。

0 0
原创粉丝点击