您的位置 首页 java

Java基础学习——Collection集合

集合类的特点

提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

集合类的体系图

集合体系图

Collection集合概述

  • 是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
  • JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

Collection集合的遍历

迭代器 遍历:

  1. iterator iterator():返回此集合中元素的 迭代 器,通过集合的iterator()方法得到。
  2. 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
 Iterator<Student> it=c.iterator();
		while(it.hasNext()) {
			Student s=it.next();
			System.out.println(s.getName()+","+s.getAge());
		}  

普通for遍历:

 //普通for遍历
		for(int i=0;i<c.size();i++) {
			Student s = ((ArrayList<Student>) c).get(i);
			System.out.println(s.getName()+","+s.getAge());
		}  

增强for遍历:

 for(Student s:c) {
			System.out.println(s.getName()+","+s.getAge());
		}  

案例讲解

创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

创建学生类:

 public class Student {
	 private  String name;
	private int age;
	
	public Student() {
	}
	
	public Student(String name,int age) {
		this.name=name;
		this.age=age;
	}
	
	public String getName() {
		return name;
	}
	
	public  void  setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
}  

在main方法中分别使用上述三种方式进行遍历:

 public  static  void main(String[] args) {
		Collection<Student> c = new ArrayList<>();
		
		//创建学生对象
		Student s1=new Student("it01", 20);
		Student s2=new Student("it02", 21);
		Student s3=new Student("it03", 22);
		
		//把学生添加到集合中
		c.add(s1);
		c.add(s2);
		c.add(s3);
		
		//遍历集合(迭代器方式)
  //Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
		Iterator<Student> it=c.iterator();
  
  //用 while 循环改进元素的判断和获取
		while(it.hasNext()) {
			Student s=it.next();
			System.out.println(s.getName()+","+s.getAge());
		}
		
		System.out.println("--------");
		
		
		//普通for遍历
		for(int i=0;i<c.size();i++) {
			Student s = ((ArrayList<Student>) c).get(i);
			System.out.println(s.getName()+","+s.getAge());
		}
		System.out.println("--------");
		
	    //增强for遍历
		for(Student s:c) {
			System.out.println(s.getName()+","+s.getAge());
		}
	}
	
  

结果显示:

结果显示

文章来源:智云一二三科技

文章标题:Java基础学习——Collection集合

文章地址:https://www.zhihuclub.com/198818.shtml

关于作者: 智云科技

热门文章

网站地图