转载请注明出处
http://blog.csdn.net/pony_maggie/article/details/44786233
作者:小马
public class FillingList { /** * @param args * fill只会对已经存在空间填充,所以下面的for循环必不可少 */ public static void main(String[] args) { // TODO Auto-generated method stub List<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { list.add(""); } Collections.fill(list, "hello"); System.out.println(list); } }
public static void main(String[] args) { ArrayList cats = new ArrayList(); for(int i = 0; i < 7; i++) { cats.add(new Cat(i)); } for(int i = 0; i < 7; i++) { ((Cat)cats.get(i)).print(); }
public class CatsAndDogs { /** * @param args */ public static void main(String[] args) { ArrayList cats = new ArrayList(); for(int i = 0; i < 7; i++) { cats.add(new Cat(i)); } cats.add(new Dog(7)); for(int i = 0; i < 7; i++) { ((Cat)cats.get(i)).print(); } for(int i = 0; i < cats.size(); i++) { ((Cat)cats.get(i)).print(); } //dog is detected at run time } }
public class MouseList { private ArrayList list = new ArrayList(); public void add(Mouse m) { list.add(m); } public Mouse get(int index) { return (Mouse)list.get(index); } public int size() { return list.size(); } }
思考一个问题,如果采用上面这种封装的形式,而是继承ArrayList,能不能达到同样的效果呢?