Java学习-集合框架-Collection父接口

Java学习-集合框架

什么是集合
对象的容器,定义了对多个对象进行操作的方法,可实现数组的功能。
和数组的区别:
1.数组长度固定,集合长度可变
2.数组可以存储基本类型和引用类型,集合只能存储引用类型

Collection体系集合

List接口:有序、有下标、元素可重复,ArrayList、LinkedList、Vector
Set接口:无序、无下标、元素不能重复,HashSet、SortedSet、TreeSet

Collection父接口

代表一组任意类型的对象,无序、无下标、不能重复
1.boolean add(Object obj):添加一个对象
2.boolean addAll(Collection c):添加集合中的所有对象
3.void clear():清空所有对象
4.boolean contains(Object o):检查是否包含此对象
5.boolean equals(Object o):比较是否与此对象相等
6.boolean isEmpty():判断是否为空
7.boolean remove(Object o):移除对象
8.int size():返回集合中元素个数
9.Object[] toArray():将集合转为数组
案例1:

Collection collection = new ArrayList();
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
sout(collection.size());//→ 3
sout(collection)//→ [苹果,西瓜,榴莲]
collection.remove("苹果");
sout(collection.size());//→ 2
collection.clear();
sout(collection.size());//→ 0
for(Object object:collection){sout(object);}//→ 苹果 \n 西瓜 \n 榴莲
Iterator it = collection.iterator();
// hasNext()、next()、remove()
while(it.hasNext()){
	String s = (String)it.next();
	sout(s);
	//collection.remove(s);//→ ConcurrentModificationException,不能使用 collection 的 remove()
	//it.remove(s);//可以使用 it 的 remove()
}//→ 苹果 \n 西瓜 \n 榴
sout(collection.contains("西瓜"));//→ true
sout(collection.isEmpty());//→ false

案例2:

public class Student{
	private String name;
	private int age;
	//有参构造、无参构造、get、set、toString
}
public class Demo{
	public static void main(String[] args){	
		Collection collection = new ArrayList();
		Student s1 = new Student("张三"20);
		Student s2 = new Student("李四"21);
		collection.add(s1);
		collection.add(s2);
		sout(collection.seze());//→ 2
		sout(collection.toString());//→ [Student[name=张三,age=20],Student[name=李四,age=21]]
		collection.remove(s1);
		collection.remove(new Student("张三",20));//→ 不能删除
		sout(collection.seze());//→ 1

		for(Object object:collection){Sutdent s = (Student)object;sout(s.toString());}
		//→ Student[name=张三,age=20]] \n Student[name=李四,age=21]]
		Iterator it = collection.iteartor;
		while(it.hasNext()){Sutdent s = (Student)object;sout(s.toString());}
		//→ Student[name=张三,age=20]] \n Student[name=李四,age=21]]
		collection.contains(s1);//→ true
		collection.contains(new Student("张三",20));//→ false
		collection.clear();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值