/* 集合常用方法: add() 向列表的尾部添加指定的元素(可选操作)。 size() 返回列表中的元素数。 clear() 移除集合中所有元素 contains() 判断集合中是否包含某个元素 返回true or false 底层调用equals方法 remove(index) 移除指定位置集合中的元素 返回这个元素 remove(Object o)移除集合中第一次出现某个指定的元素 返回true or false 底层调用equals方法 isEmpty() 判断集合是否为空 */ public class CollectionTest01 { public static void main(String[] args) { List list = new ArrayList(); List list1 = new ArrayList(); // 向集合中添加元素使用add()方法 list.add(123); list.add(12.3); list.add(123); list.add(new Object()); list.add("123"); // 返回集合的元素个数 System.out.println("list 长度 = " + list.size()); list1.addAll(list); // 清空集合 list.clear(); System.out.println("集合元素个数是:" + list.size()); // 获取迭代器对象 Iterator iterator = list.iterator(); /* while(iterator.hasNext()){ Object o = iterator.next(); System.out.println(o); } */ // 遍历集合中所有元素 for (Object o:list1 ) { System.out.println(o); } // 判断集合中是否包含某个元素、 System.out.println(list1.contains("123")); System.out.println(list1.contains("zhangsan")); // 移除指定元素 boolean res = list1.remove("123"); System.out.println(res); // 移除指定位置元素 System.out.println(list1.remove(0)); // 判断集合是否为空 System.out.println(list.isEmpty()); System.out.println(list1.isEmpty()); } }
JavaSE-集合 常用方法
最新推荐文章于 2024-06-13 08:37:22 发布