Collection常用方法

package cn.itcast.collection;

import java.util.ArrayList;
/*
 	查看:	
		contains(Object o) 
		containsAll(Collection<?> c)    如果此 collection 包含指定 collection 中的所有元素,则返回 true
		isEmpty()    如果Collection不包含任何的元素,则返回true,否则返回false.
		size()      查看集合中的元素个数
	
	

 */
import java.util.Collection;

class Person{
	
	int id;
	
	String name;

	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "{身份证:"+ this.id+" 姓名:"+ this.name+"}";
	}
	
	@Override
	public boolean equals(Object obj) {
		Person p  = (Person)obj;
		return this.id == p.id;
	}
}

class Dog{}


public class Demo3 {
	
	public static void main(String[] args) {
		Collection c = new ArrayList();  //接口关系下的多态, 方法都是使用了接口实现类的方法,
		//添加元素
		c.add(new Person(110,"狗娃"));
		c.add(new Person(112,"狗剩"));
		c.add(new Person(119,"铁蛋"));
		
		
		//在现实圣湖中只有身份证编号一致,则是同一个人
	/*	Person p = new Person(110,"狗娃"); 
		System.out.println("包含该元素吗?"+ c.contains(p));  //  contains 方法底层是依赖了equals方法进行比较的。
		
		
		Collection c2 = new ArrayList();
		c2.add(new Person(110,"狗娃"));
		c2.add(new Person(112,"狗剩"));
		System.out.println("包含集合中的所有元素吗?"+ c.containsAll(c2));
		
		c.clear();
		c.add(null);
		System.out.println("c集合是空 元素吗?"+ c.isEmpty());
		*/
		
		
		System.out.println("集合的元素个数:"+ c.size());
		
		
		
		
		System.out.println("集合的元素:"+ c);
		
		
	}
	
}

猜你喜欢

转载自blog.csdn.net/sunhongfu123/article/details/84853246