Java 5 之前沒有辦法宣告Type safe的collections。需要建立一個 String 的 ArrayList,是無法使用角括號的,因此只能寫成:
ArrayList myList = new ArrayList(); List myList = new ArrayList();
class Parent {} class Child extends Parent {} List <Parent> myList = new ArrayList <Child> ();
以下兩種也都是錯誤範例:
List<Object>myList=newArrayList<JButton>();
List<Number> numbers = new ArrayList<Integer>();
正確範例:
List<JButton> myList = new ArrayList<JButton>();
List<Object> myList = new ArrayList<Object>();
List<Integer> myList = new ArrayList<Integer>();
多型只能用在base,也就是collections的type,如:
List<JButton> myList = new ArrayList<JButton>();
Object[] myArray = new JButton[3];
以下程式碼將無法編譯成功,原因是試圖將int及string加入TreeSet,但TreeSet會去排序,所以當他不知道如何排序String和int時,將會拋出ClassCastException
public class Test3 { public static void main(String[] args){ Set set = new HashSet(); //Cannot add string and int to the same TreeSet, but HashSet is ok. set.add("2"); set.add(3); set.add("1"); Iterator it = set.iterator(); while(it.hasNext()){ System.out.print(it.next() + " "); //TreeSet is trying do sort, so ClassCastException shows } } }
沒有留言:
張貼留言