package com.lin.test_; import java.util.ArrayList; import java.util.Iterator; public class text2 { public static void main(String[] args) { ArrayList list = new ArrayList(); Car car = new Car("宝马", "400000"); Car car2 = new Car("宾利", "5000000"); //add:添加单个元素 list.add(car); list.add(car2); System.out.println("1 " + list); //remove:删除指定元素 list.remove(1); System.out.println("2 " + list); //contains:查找元素是否存在 System.out.println("3 " + list.contains(car)); //size:获取元素个数 System.out.println("4 " + list.size()); //isEmpty:判断是否为空 System.out.println("5 " + list.isEmpty()); //clear:清空 list.clear(); System.out.println("6 " + list); //addAll:添加多个元素 list.add(car); list.add(car2); list.addAll(list); System.out.println("7 " + list); //containsAll:查找多个元素是否“都”存在 ArrayList list1 = new ArrayList(); list1.add(car); list1.add(new Car("AE86", "1000000")); System.out.println("8 " + list.containsAll(list1)); //removeAll:删除多个元素 list.removeAll(list1); System.out.println("9 " + list); //使用增强for循环遍历 System.out.println("10 "); list.addAll(list1); for (Object obj: list){ System.out.println(obj); } //使用迭代器遍历 System.out.println("11 "); Iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } } class Car { private String name; private String price; public Car(String name, String price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "Car{" + "name=" + name + ", price=" + price + '}'; } }