Set集合小结


 Set集合和List集合的区别?
Set集合:不允许元素重复,唯一的(元素可以为null) ,不能保证迭代的顺序恒久不变(底层哈希表和hascode)
无序(存储和取出不一致)
List:允许元素重复,并且存储特点:有序性(存储和取出一致)

                通过Set集合存储字符串并遍历

public class SetDemo1 {

	public static void main(String[] args) {
		
		//创建集合对象
		Set <String> set = new HashSet<String>();

		//添加元素
		set.add("hello") ;
		set.add("java") ;
		set.add("world") ;
		//看他的唯一性,多存储一些元素
		set.add("hello") ;
		set.add("java") ;
		set.add("world") ;
		
		//遍历
		for(String s: set) {
			System.out.println(s);
		}
	}
}

输出只有唯一的元素

 HashSet集合的add方法底层依赖于双列集合HashMap,它依赖于两个方法,HashCode()方法和equals()方法
   先比较字符串的HashCode()码值一样,再比较equals()方法
  如果hasCode码值一样,还要比较内容是否相同,由于存储String,重写了equals()方法

  String本身重写了equals方法,所以不需要再重写了!

练习

 set集合存储自定义对象并遍历
现在是自定义的类,HashSet集合的add()方法本身依赖于hashCode()和equals()方法

在Student类中并没重写这两个方法,解决,重写这两个方法

public class SetDemo3 {

	public static void main(String[] args) {
		Set<Student> set = new HashSet<Student>() ;
		
		//创建学生对象
		Student s1 = new Student("高圆圆", 27) ;
		Student s2 = new Student("高圆圆", 28) ;
		Student s3 = new Student("文章", 30) ;
		Student s4 = new Student("马伊琍", 39) ;
		Student s5 = new Student("高圆圆", 27) ;
		
		//存储到集合中
		set.add(s1) ;
		set.add(s2) ;
		set.add(s3) ;
		set.add(s4) ;
		set.add(s5) ;
		
		//遍历
		for(Student s : set) {
			System.out.println(s.getName()+"---"+s.getAge());
		}
	}
	}
创建Student类并且重写hashCode()和equals()方法
public class Student {
private String name ; 
private int age ;
public Student(String name, int age) {
	super();
	this.name = name;
	this.age = age;
}
public Student() {
	super();
	

}
/**
 * @return the name
 */
public String getName() {
	return name;
}
/**
 * @param name the name to set
 */
public void setName(String name) {
	this.name = name;
}
/**
 * @return the age
 */
public int getAge() {
	return age;
}
/**
 * @param age the age to set
 */
public void setAge(int age) {
	this.age = age;
}
/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + age;
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	return result;
}
/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Student other = (Student) obj;
	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;
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值