黑马程序员技术交流社区
标题: 求HashSet 和 TreeSet 确定集合唯一性的原理 [打印本页]
作者: ⋛⋋⊱⋋飞☠扬 时间: 2012-11-26 23:06
标题: 求HashSet 和 TreeSet 确定集合唯一性的原理
求HashSet 和 TreeSet 确定集合唯一性的原理 求代码详解 谢谢
作者: 齐银春 时间: 2012-11-26 23:14
实现equals 和hasCode方法 经过equals判断后,如果相同再用hasCode判断
将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。
package cn.itcast.api.p2.map.test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import cn.itcast.bean.Student;
public class TreeMapTest {
/**
* @param args
*/
public static void main(String[] args) {
/*
*
* 需求:
* 将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。
* 学生对象中包含着姓名和年龄这样的属性。
* 归属地:这里仅用字符串表示即可。
*
* 思路:
* 1,对学生对象进行描述。同姓名同年龄视为同一人。
*
*/
TreeMap<Student,String> tm = new TreeMap<Student,String>(new Comparator<Student>(){
public int compare(Student s1,Student s2){
int temp = s1.getName().compareTo(s2.getName());
return temp==0?s1.getAge()-s2.getAge():temp;
}
});
tm.put(new Student("xiaoming1",28), "北京");
tm.put(new Student("xiaoming7",23), "天津");
// tm.put(new Student("xiaoming7",23), "西藏");
tm.put(new Student("xiaoming2",25), "河北");
tm.put(new Student("xiaoming0",24), "河南");
//用keyset()取出。
// Iterator<Student> it = tm.keySet().iterator();
Set<Student> keySet = tm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext()){
Student key = it.next();
String addr = tm.get(key);
System.out.println(key.getName()+"::::"+key.getAge()+":::"+addr);
}
}
}
package cn.itcast.bean;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
/**
* 定义Student的hashCode的方法。
*/
public int hashCode(){
final int NUMBER = 37;
return name.hashCode()+age*NUMBER;
}
/**
* 定义Student的equals方法。
*/
public boolean equals(Object obj){
if(this == obj)
return true;
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配,无法比较");
Student stu = (Student)obj;
return this.name.equals(stu.name) && this.age == stu.age;
}
/**
* @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;
}
@Override
public int compareTo(Student o) {
int temp = this.age - o.age;
return temp==0?this.name.compareTo(o.name):temp;
}
}
作者: 齐银春 时间: 2012-11-26 23:15
将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import cn.itcast.bean.Student;
public class TreeMapTest {
/**
* @param args
*/
public static void main(String[] args) {
/*
*
* 需求:
* 将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。
* 学生对象中包含着姓名和年龄这样的属性。
* 归属地:这里仅用字符串表示即可。
*
* 思路:
* 1,对学生对象进行描述。同姓名同年龄视为同一人。
*
*/
TreeMap<Student,String> tm = new TreeMap<Student,String>(new Comparator<Student>(){
public int compare(Student s1,Student s2){
int temp = s1.getName().compareTo(s2.getName());
return temp==0?s1.getAge()-s2.getAge():temp;
}
});
tm.put(new Student("xiaoming1",28), "北京");
tm.put(new Student("xiaoming7",23), "天津");
// tm.put(new Student("xiaoming7",23), "西藏");
tm.put(new Student("xiaoming2",25), "河北");
tm.put(new Student("xiaoming0",24), "河南");
//用keyset()取出。
// Iterator<Student> it = tm.keySet().iterator();
Set<Student> keySet = tm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext()){
Student key = it.next();
String addr = tm.get(key);
System.out.println(key.getName()+"::::"+key.getAge()+":::"+addr);
}
}
}
package cn.itcast.bean;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
/**
* 定义Student的hashCode的方法。
*/
public int hashCode(){
final int NUMBER = 37;
return name.hashCode()+age*NUMBER;
}
/**
* 定义Student的equals方法。
*/
public boolean equals(Object obj){
if(this == obj)
return true;
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配,无法比较");
Student stu = (Student)obj;
return this.name.equals(stu.name) && this.age == stu.age;
}
/**
* @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;
}
@Override
public int compareTo(Student o) {
int temp = this.age - o.age;
return temp==0?this.name.compareTo(o.name):temp;
}
}
作者: 刘文飞 时间: 2012-11-26 23:23
好像没听过集合唯一性呢?什么意思啊:L
作者: 宫明星 时间: 2012-11-26 23:26
HashSet是如何保证元素唯一性的呢?
是通过元素的两个方法,hashCode和equals来完成。
如果元素的HashCode值相同,才会判断equals是否为true。
如果元素的hashcode值不同,不会调用equals。
作者: 徐大鹏 时间: 2012-11-26 23:38
区别
1. HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的,只不过Set用的只是Map的key
2. Map的key和Set都有一个共同的特性就是集合的唯一性.TreeMap更是多了一个排序的功能.
3. hashCode和equal()是HashMap用的, 因为无需排序所以只需要关注定位和唯一性即可.
a. hashCode是用来计算hash值的,hash值是用来确定hash表索引的.
b. hash表中的一个索引处存放的是一张链表, 所以还要通过equal方法循环比较链上的每一个对象 才可以真正定位到键值对应的Entry.
c. put时,如果hash表中没定位到,就在链表前加一个Entry,如果定位到了,则更换Entry中的value,并返回旧value
4. 由于TreeMap需要排序,所以需要一个Comparator为键值进行大小比较.当然也是用Comparator定位的.
a. Comparator可以在创建TreeMap时指定
b. 如果创建时没有确定,那么就会使用key.compareTo()方法,这就要求key必须实现Comparable接口.
c. TreeMap是使用Tree数据结构实现的,所以使用compare接口就可以完成定位了.
用法- import java.util.TreeSet;
- import java.util.Iterator;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashSetTest {// java 中Set的使用(不允许有重复的对象):
- public static void main(String[] args) {
- HashSetTest hashSet = new HashSetTest();
- String a = new String("A");
- String b = new String("B");
- String c = new String("B");
- hashSet.add(a);
- hashSet.add(b);
- System.out.println(hashSet.size());
- String cz=hashSet.add(c)?"此对象不存在":"已经存在";
- System.out.println("测试是否可以添加对象 "+cz);
- System.out.println(hashSet.isEmpty());
- //测试其中是否已经包含某个对象
- System.out.println(hashSet.contains("A"));
- Iterator ir=hashSet.iterator();
- while(ir.hasNext()) {
- System.out.println(ir.next());
- } //测试某个对象是否可以删除
- System.out.println(hashSet.remove("a"));
- System.out.println(hashSet.remove("A"));
- //经过测试,如果你想再次使用ir变量,必须重新更新以下
- ir=hashSet.iterator();
- while(ir.hasNext()) {
- System.out.println(ir.next());
- }
- }
- }
- /** * 通过这个程序,还可以测试树集的添加元素的无序性与输出的有序性 */
- class TreeSetTest {
- public void main(String[] args) {
- TreeSet tree = new TreeSet();
- tree.add("China");
- tree.add("America");
- tree.add("Japan");
- tree.add("Chinese");
- Iterator iter = tree.iterator();
- while (iter.hasNext()) {
- System.out.println(iter.next());
- }
- }
- }
复制代码
作者: 张硕 时间: 2012-11-26 23:46
HashSet是一种基于哈希表的结构的一种集合类,由于哈希表的底层实现是使用了hashCode和equals两个方法来完成的,所以想要保证唯一性就要重写这两个方法,而且为了提高效率尽量让在比较哈希码的时候就比较出结果。
TreeSet这个集合的底层是基于二叉树的数据结构,而它确定唯一性可以用两种方法一个是在集合里面创建一个:Comparator 的比较器的匿名内部类调用compare方法
第二种是让定义的类实现Comparable接口,重写compareTo方法来实现
作者: 彭璞 时间: 2012-11-27 21:30
楼上的讲的已经很好了 我在补充一点hashcade的知识:
hash表:讲解哈希表,就需要与一般的数组作对比的讲,这样更能说明哈希表。
我们都知道,数组是一个下标(数字)与一个值得对应,给出数组某一合法下标,就会得到数组在这个下标下存储的值;而哈希表就类似是用名字代替下标的一个特殊的数组。只要给出哈希表中某一个合法名字的值,就能找到与这个名字对应的,哈希表中的一个值。
举个例子说明数组与哈希表:
有一个数组array,他有3个元素,这个数组存储了3个城市的当天的气温,array[0]=“-1摄氏度”,array[1]=“3摄氏度”,array[2]=“12摄氏度”,这样的数组,除了程序员以外,几乎没有人知道,那个城市的气温是多少,但是如果用哈希表存储,就能一目了然了。哈希表 hash
hash.add(“北京”,“-1摄氏度”),hash.add(“上海”,“3摄氏度”),hash.add(“广州”,“12摄氏度”),看到了吧,这样,城市名字就和相应的气温对应上了,哈希表中,第一个参数就是哈希表元素的坐标,又叫键名,第2个参数就是值,又叫键值。
哈希表也可以和数组一样,能够动态的随机存储,但是比一般数组要能节省空间,但是浪费了时间。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |