package shujia1115.Arraylistdemo;
/*Arraylist对象对的创建,遍历及删除等基本操作
*/
import java.util.ArrayList;
import java.util.List;
public class Arraylist {
public static void main(String[] args) {
List list =new ArrayList();
Dog dog=new Dog("毛毛","泰迪");
Dog dog1=new Dog("蛋蛋","拉布拉多");
Dog dog2=new Dog("球球","柴犬");
Dog dog3=new Dog("二哈","哈士奇");
//添加对象,直接添加
list.add(dog);
list.add(dog1);
list.add(dog2);
//通过指定索引添加对象,原有数据自动后退
list.add(2,dog3);
System.out.println("一共有"+list.size()+"只犬");
//遍历集合
for(int i= 0; i<list.size();i++){
//创建狗狗对象,接收集合中的数据
Dog dmo= (Dog) list.get(i); //强制类型转换,子类转父类
System.out.println("狗狗名称为:"+dmo.getName()+"\t狗狗品种为:"+ ((Dog) list.get(i)).breed);
}
//删除集合对象
list.remove(dog);
System.out.println("删除了毛毛");
System.out.println("还有有"+list.size()+"只犬");
System.out.println("查看毛毛是否还在:"+list.contains(dog));
System.out.println("剩下狗狗信息为:");
for(int i = 0;i<list.size();i++){
Dog dem1 = (Dog) list.get(i);
System.out.println("狗狗名称为:"+dem1.getName()+"\t狗狗品种为:"+dem1.breed);
}
}
}
//Dog类如下:
package shujia1115.Arraylistdemo;
/*狗类
*/
public class Dog {
//构造方法
public Dog(String name,String breed){
this.name=name;
this.breed=breed;
}
String name;
String breed; //品种
public String getName(){
return name;
}
public String getBreed(){
return breed;
}
}
程序运行结果: