`
shoushounihao
  • 浏览: 39490 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Set集合中hashcode哈希理解

    博客分类:
  • java
 
阅读更多

package com.itcast.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


/**
 *
 * Set:元素不可以重复,是无序。
 Set接口中的方法和Collection一致。
 |--HashSet: 内部数据结构是哈希表 ,是不同步的。
  如何保证该集合的元素唯一性呢?
  是通过对象的hashCode和equals方法来完成对象唯一性的。
  如果对象的hashCode值不同,那么不用判断equals方法,就直接存储到哈希表中。
  如果对象的hashCode值相同,那么要再次判断对象的equals方法是否为true。
  如果为true,视为相同元素,不存。如果为false,那么视为不同元素,就进行存储。
  
  记住:如果元素要存储到HashSet集合中,必须覆盖hashCode方法和equals方法。
  一般情况下,如果定义的类会产生很多对象,比如人,学生,书,通常都需要覆盖equals,hashCode方法。
  建立对象判断是否相同的依据。

 *
 */

public class HashDemo1 {

 
 
 public static void main(String args[])
 {
  Set set=new HashSet();
  set.add(new StudentBean(12, "list1"));
  set.add(new StudentBean(13, "list2"));
  set.add(new StudentBean(14, "list3"));
  set.add(new StudentBean(12, "list1"));
  Iterator it=set.iterator();
  while(it.hasNext())
  {
   StudentBean stu=(StudentBean)it.next();
   System.out.println(stu.getName()+"age"+stu.getAge());
  }
 }
}

 

 

package com.itcast.set;

public class StudentBean {

 private int age;
 private String name;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public StudentBean(int age, String name) {
  super();
  this.age = age;
  this.name = name;
 }
 public StudentBean() {
  super();
 }
 @Override
 public boolean equals(Object obj) {
  
  if(this==obj)
  {
   return true;
  }
  if(!(obj instanceof StudentBean) )
  {
   throw new ClassCastException("类型不对");
  }
  
  StudentBean stu=(StudentBean)obj;
  return this.name.equals(stu.getName())&&this.age==stu.age;
 }
 @Override
 public int hashCode() {
  
  return name.hashCode()+this.age*37;
 }
 @Override
 public String toString() {
  
  return this.name+":"+this.age;
 }
 
 
}

 

 

 

 

package com.itcast.set;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo1 {
 /*
  * 定义功能去除ArrayList中的重复元素。
  */
 /**
  * @param args
  */
 public static void main(String[] args) {

  List list=new ArrayList();
  list.add("abc");
  list.add("abc2");
  list.add("abc2");
  getSingleList(list);
  
  List list2=new ArrayList();
  list2.add(new StudentBean(12, "aa"));
  list2.add(new StudentBean(13, "aa2"));
  list2.add(new StudentBean(12, "aa"));
  getSingleList(list2);
 }

 private static void getSingleList(List list) {
  // TODO Auto-generated method stub
  ArrayList temp=new ArrayList();
  Iterator it=list.iterator();
  while(it.hasNext())
  {
   Object obj=it.next();
   if(!temp.contains(obj))
   {
    temp.add(obj);
   }
  }
  System.out.println(temp);
 }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics