标题: 19行代码理解java中的泛型 [打印本页] 作者: gezhizheng 时间: 2015-1-28 16:35 标题: 19行代码理解java中的泛型 在项目开发中我们会不可避免的使用到泛型,java中的泛型对于初学者来说比较难理解,希望这个帖子能够引入高手对于java泛型的讨论。
一下是我理解中泛型的作用:
public class Holder<A, B> {
public final A a;
public final B b;
public Holder(A a, B b) {
this.a = a;
this.b = b;
}
public static void main(String args[]) {
String first = "This is a member of class Holder named A";
String second = "This is a member of class Holder named B";
Holder<String, String> holder = new Holder<String, String>(first,
second);
System.out.println(holder.a);
System.out.println(holder.b);
}
}
以上泛型的作用之一:一个方法返回两个参数。
看了一下的代码你就会明白如何使用java泛型实现“一个方法返回两个参数”
public Holder<int,String>getTwoParameters(){
int first=0;
String second ="I am the second parameter";
return new Holder<int,String>(first,second);
}
相当简单,如果你要在代码中获取这两个参数,也相当方便:
Holder<int,String> holder= getTwoParameters();
int first = holder.first;
String second = holder.second;