一
在面向對象編程語言中
對比一下以下代碼:
public class GenericTest
private Object a;
public GenericTest
this
}
public Object getA()
return a;
}
public void setA(Object a)
this
}
public static void main(String[] args)
GenericTest
String str = (String)g
g
Integer x = (Integer) g
}
}
public class GenericTest
private T a;
public GenericTest
this
}
public T getA()
return a;
}
public void setA(T a)
this
}
public static void main(String[] args)
GenericTest
String str = g
// 編譯時錯誤
g
}
}
從兩段程序的①可以看出
所以
二
泛型也可以應用於接口
public interface GenericInterface <T>
T next();
}
public class GenericTest
private int[] a;
private int size;
private int pos =
private int addPos =
public GenericTest
this
a = new int[sz];
}
public Integer next()
if ( pos > addPos
pos =
}
return a[pos++];
}
public boolean hasNext()
return !(pos == addPos);
}
public boolean add(int value)
if ( addPos >= size )
return false;
}
else
a[addPos++] = value;
return true;
}
}
public int getSize()
return size;
}
}
public class GenericTest
private String[] a;
private int size;
private int pos =
private int addPos =
public GenericTest
this
a = new String[sz];
}
public String next()
if ( pos > addPos
pos =
}
return a[pos++];
}
public boolean hasNext()
return !(pos == addPos);
}
public boolean add(String value)
if ( addPos >= size )
return false;
}
else
a[addPos++] = value;
return true;
}
}
public int getSize()
return size;
}
}
public class GenericTest
public static void main(String[] args)
GenericTest
GenericTest
String[] values =
for (int i =
g
}
for (int i =
g
}
while(g
System
}
while(g
System
}
}
}
這裡需要注意一點
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27307.html