优秀的编程知识分享平台

网站首页 > 技术文章 正文

Java基础学习——Collection集合 java中的collection

nanyue 2024-12-18 16:02:16 技术文章 4 ℃

集合类的特点

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

集合类的体系图

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());
		}
	}
	

结果显示:

Tags:

最近发表
标签列表