您的位置:首页 > 其它

泛型

2015-06-26 17:48 190 查看


泛型 构造方法中使用

class Gener<T>{
private T value;

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}
public String toString(){
return this.getValue().toString();
}
}

public class Demo01 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Gener<String> g = new Gener<String>();
g.setValue("Hello World");
say(g);
}
public static void say(Gener<?> g){
System.out.println(g.toString());
}

}


  泛型 通配符的使用:

使用泛型时,如果事先不知道是什么类型,可以使用?通配符

class Gener<T>{
private T value;

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}
public String toString(){
return this.getValue().toString();
}
}

public class Demo01 {

public static void main(String[] args) {

Gener<String> g = new Gener<String>();
g.setValue("Hello World");
say(g);
}
public static void say(Gener<?> g){
System.out.println(g.toString());
}

}


  泛型接口:

interface Gener1<T> {
public void say();
}

class Gar<T> implements Gener1<T> {
private String value;

public Gar(String value) {
this.value = value;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

@Override
public void say() {

}

}

public class Demo02 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Gar<String> g = new Gar<String>("Hello World");
System.out.println(g.getValue());
}

}


  泛型方法:

泛型方法中可以定义泛型参数,此时,参数的类型就是传入数据类型

class Genera {
public <T> T say(T t) {
return t;
}
}

public class Demo03 {

public static void main(String[] args) {
Genera g = new Genera();
String result = g.say("Hello World");
int result1 = g.say(10);
System.out.println(result);
System.out.println(result1);
}

}


  泛型数组:

public class Demo04 {

public static void main(String[] args) {
Integer arr[] = { 1, 2, 3, 4 };
d(arr);
String a[] = { "Hello", "World", "Gracy" };
d(a);
}

public static <T> void d(T arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: