Java集合框架(Collection)
集合
-
对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。 和数组区别: 数组长度固定,集合长度不固定 数组可以存储基本类型和引用类型;集合只能存储引用类型,如果要存储基本类型,对基本类型进行装箱 位置:java.util.*;
Collection 体系集合
Collection父接口
-
方法: boolean add(Object obj)//添加一个对象 boolean addAll(Collection c)//将一个集合中的对象添加到此集合中 void clear()//清空此集合中的所有对象 boolean contains(Object o)//检查此集合中是否包含o对象 boolean equals(Object o)//比较此集合是否与指定对象相等 boolean isEmpty()//判断此集合是否为空 boolean remove(Object o)//在此集合中移除o对象 int size()//返回此集合中的元素个数 Object[] toArray()//将此集合转换成数组
字符串
public static void main(String[] args) { //创建集合 Collection collection = new ArrayList<>(); //添加元素 collection.add("apple"); collection.add("melon"); collection.add("oriange"); System.out.println(collection.size()); System.out.println(collection); //删除元素 //collection.remove("apple"); //System.out.println(collection); //清空 //collection.clear(); //System.out.println(collection); //遍历元素(重点)方法1:增强for for (Object object:collection) { System.out.println(object); } //方法2:使用迭代器(专门用来遍历集合) //hasNext()判断是否有下一个元素 //next()返回迭代中的下一个元素 //remove()删除当前元素 Iterator iterator = collection.iterator(); while (iterator.hasNext()){ String next = (String) iterator.next(); System.out.println(next); //不能使用collection.remove()方法 //iterator.remove(); } System.out.println(collection.size()); //判断 System.out.println(collection.contains("melon")); System.out.println(collection.isEmpty()); }
保存学生信息
public static void main(String[] args) { //新建collection对象 ArrayList<Object> objects = new ArrayList<>(); Student s1 = new Student("su", 10); Student s2 = new Student("zi", 18); Student s3 = new Student("xian", 25); //添加数据 objects.add(s1); objects.add(s2); objects.add(s3); System.out.println("元素个数:"+objects.size()); System.out.println(objects); //遍历 for (Object obj:objects ) { Student s = (Student) obj; System.out.println(s); } Iterator<Object> iterator = objects.iterator(); while (iterator.hasNext()){ Student s = (Student) iterator.next(); System.out.println("迭代:"+s); }
下一篇:
c语言,十六进制转十进制