Java学习笔记 集合

Collection体系

什么是集合

  • 对象的容器,定义了对多个对象进行操作的常用方法。可以实现数组的功能
  • 和数组的区别
    • 数组长度固定,集合长度不固定
    • 数组可以存储基本类型和引用类型,集合只能存储引用类型

Collection体系

img

  • List接口:有序、有下标、元素可以重复
  • Set接口:无序、无下标、元素不可重复

常用方法

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo1 {
	public static void main(String[] args) {
		//创建集合
		Collection collection = new ArrayList();

		//添加元素
		collection.add("cehncehn");
		collection.add("jj");
		System.out.println(collection.size());
		System.out.println(collection.toString());

		//删除元素
		/*
		collection.remove("cehncehn");
		collection.clear();
		System.out.println(collection.size());
		 */

		//遍历元素
		for (Object o : collection) {
			System.out.println(o);
		}

		//迭代器:专门遍历集合
		/*
		hasNext():有没有下一个元素
		next():获取下一个元素
		remove():删除当前元素
		 */
		Iterator it = collection.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
			//collection.remove(it.next()); //ConcurrentModificationException
			// 迭代器使用期间禁止使用collection方法改变元素
		}

		//判断
		System.out.println(collection.contains("jj"));
		System.out.println(collection.isEmpty());

	}
}

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

	@Override
	public String toString() {
		return "Student [name="+ name + ",age=" + age + "]";
	}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * Collection使用:保存学生信息
 */

public class Demo02 {
	public static void main(String[] args) {
		Collection collection=new ArrayList();
		Student s1=new Student("张三",20);
		Student s2=new Student("无忌",18);
		Student s3=new Student("王二",22);

		collection.add(s1);
		collection.add(s2);
		collection.add(s3);
		System.out.println(collection.size());
		System.out.println(collection.toString());

		Iterator it = collection.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}

		for (Object o : collection) {
			System.out.println(o);
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值