ArrayList集合

创建两个文件Dog.java和ArrayLTest.java

class Dog 

public class Dog {
    private String name;
    private String pz;
    Dog(String name, String pz){
        this.name=name;
        this.pz=pz;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPz() {
        return pz;
    }

    public void setPz(String pz) {
        this.pz = pz;
    }

    @Override
    public String toString() {//重写tostring,如果不重写,遍历输出的元素是一个16进制的地址,快捷键idea右键tostring()
        return "Dog{" +
                "name='" + name + '\'' +
                ", pz='" + pz + '\'' +
                '}';
    }
}

class ArrayListTest

import java.util.ArrayList;

/**
 * Created by liwenj on 2017/7/28.
 */
class ArrayListTest {
    public static void main(String[] args) {
        ArrayList dogs = new ArrayList();
        Dog dog1 = new Dog("佳佳", "金毛");
        dogs.add(dog1);
        Dog dog2 = new Dog("乐乐", "牧羊犬");
        dogs.add(dog2);
        Dog dog3 = new Dog("美美", "哈斯其");
        dogs.add(dog3);
        System.out.println("输出集合的长度");
        int size = dogs.size();
        System.out.println(size);
        Object o = dogs.get(2);
        if (o instanceof Dog) {
            o = (Dog) dogs.get(2);
        }
        System.out.println("输出集合第二位的值");
        System.out.println(o);
        System.out.println("输出遍历的集合的值");
        for (int j = 0; j < size; j++) {
            Dog o1 = (Dog) dogs.get(j);
            System.out.println(o1);
        }
        System.out.println("增强遍历方法输出集合的值");
        for (Object temp : dogs) {
            System.out.println(temp.toString());
        }
        System.out.println("输出删除第2个元素后集合的长度(按照对象名称)");
        boolean f = dogs.remove(dog2);
        System.out.println(dogs.size());
        System.out.println("输出删除第0个元素后集合的长度(按照索引名称)");
        dogs.remove(0);
        System.out.println(dogs.size());
    }
}

操作1的输出结果如下:

posted @ 2017-07-28 11:08  斯丢皮德曼  阅读(130)  评论(0编辑  收藏  举报