在java中,數組不能放不同數據類型的值。
方法一:
多態
定義數組類型的時候定義為父類,而存進數組為父類的子類
public class test2 { public static void main(String args[]) { father []a = new father[2]; a[0] = new son(); a[1] = new son2(); } } class father{ int i = 0; } class son extends father{ int x = 0; } class son2 extends father{ int y = 0; }
方法二:
list集合
List list = new ArrayList(); list.add("abc"); list.add(123); list.add(new HashMap());
Map集合
Map集合沒有繼承Collection接口,其提供的是key到value的映射,Map中不能包含相同的key值
方法三:
泛型
List<Object> list = new ArrayList<Object>(); list.add("abc"); list.add(123); list.add(new HashMap<Integer,String>());