泛型的复习
一、认识泛型
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;
}
}
}
打印结果:
六、数组使用泛型,就几句