集合第一发Collection

一、Collection

它是一个抽象的接口,要用它的实现类来new对象,实现类如下:

它的主要方法有:


当集合中实现类是hashSet的时候,所加入元素的存储位置由hash值定,此时对象不写hash方法时用的是object的内存地址,所以每次new对象的时候,hash值可能变也可能不变。如果对象谢了hashCode方法,那么位置就定下来了。在集合中,我们一般用Iterator迭代器来枚举集合中的元素(集合的查询组件,如我们acm中用到的Scanner)。通过一个显示代码来理解Collection:

主类:

package cn.hncu.collectionDemo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class collectionDemo {
	public static void main(String[] args) {
		//new对象
		@SuppressWarnings("rawtypes")
		//Collection collection=new ArrayList();
		Collection collection=new HashSet();
		
		//增
		collection.add(1);
		collection.add(2);
		collection.add(new Person("01", "Mike", 20));
		collection.add(new Person("02", "TOm", 21));
		
		//删
		collection.remove(1);
		
		//改1
		collection.remove(1);
		collection.add(100);
		//改2
		Object[] objs=collection.toArray();
		collection.clear();
		for (int i = 0; i < objs.length; i++) {
			if(objs[i].equals(2)){
				objs[i]=500;
			}
			collection.add(objs[i]);
		}
		//查 要用迭代器
		Iterator it=collection.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}

}
Person类:

package cn.hncu.collectionDemo;

public class Person {
	private String Sno;
	private String name;
	private int age;
	public Person(String sno, String name, int age) {
		super();
		Sno = sno;
		this.name = name;
		this.age = age;
	}
	public String getSno() {
		return Sno;
	}
	public void setSno(String sno) {
		Sno = sno;
	}
	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 "Person [Sno=" + Sno + ", name=" + name + ", age=" + age + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((Sno == null) ? 0 : Sno.hashCode());
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (Sno == null) {
			if (other.Sno != null)
				return false;
		} else if (!Sno.equals(other.Sno))
			return false;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值