泛型的複習
一、認識泛型
public class GenericText{
public static void main(String[] args) {
Genericdemo<String> gd = new Genericdemo<>();
gd.setX("10");
gd.setY("20");
System.out.println(gd.getX()+"---"+gd.getY());
}
static class Genericdemo<T>{
public T x;
public T Y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return Y;
}
public void setY(T y) {
Y = y;
}
}
}
打印結果:
二、如何在構造方法中使用泛型
public class GenericText01<T>{
public static void main(String[] args) {
Genericdemo<String> gd = new Genericdemo<>("我在構造方法中使用了泛型");
System.out.println(gd.getValue());
}
static class Genericdemo<T>{
public T value;
public Genericdemo(T value) {
super();
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
}
打印結果:
三、如何使用多個泛型
public class GenericText01{
public static void main(String[] args) {
Genericdemo<String,Integer> gd = new Genericdemo<>("我在構造方法中使用了泛型",1024);
System.out.println(gd.getValue()+"----"+gd.getKey());
}
static class Genericdemo<T,k>{
public T value;
public k key;
public Genericdemo(T value) {
super();
this.value = value;
}
public T getValue() {
return value;
}
public Genericdemo(T value, K key) {
super();
this.value = value;
this.key = key;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
}
}
打印結果:
四、泛型中的通配符,用於接受各種類型
public class GenericText02<T>{
public static void main(String[] args) {
Genericdemo<String> gd = new Genericdemo<>();
gd.setValue("我在測試通配符");
tell(gd);
}
public static void tell(Genericdemo<?> gd){
System.out.println("我是傳遞過來的值,可以是任何類型: "+gd);
}
static class Genericdemo<T>{
public T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
@Override
public String toString() {
return this.getValue().toString();
}
}
}
打印結果:
五、在接口中使用泛型
interface style<T>{
public void getstyle();
}
class TTT implements style<String>{
public String valueString;
public String getValueString() {
return valueString;
}
public void setValueString(String valueString) {
this.valueString = valueString;
}
public TTT(String valueString) {
super();
this.valueString = valueString;
}
@Override
public void getstyle() {
}
}
public class GenericText04<T>{
public static void main(String[] args) {
TTT gd = new TTT("我在這裏用了接口泛型");
System.out.println(gd.getValueString());
}
}
打印結果:
六、泛型方法的使用
public class GenericText03<T>{
public static void main(String[] args) {
Genericdemo<String> gd = new Genericdemo<>();
String s = gd.tell("A");
System.out.println("我傳的是字符"+s);
int num = gd.tell(1024);
System.out.println("我傳的是數字"+num);
}
static class Genericdemo<T>{
public <T> T tell(T t){
return t;
}
}
}
打印結果:
六、數組使用泛型,就幾句