2020-12-24

关于JAVA Set接口中HashSet的使用

Set中不能出现重复的元素,
例如将hello world转成字符串数组,
[‘h’, ‘e’,‘l’,‘l’,‘o’,‘w’,‘o’,‘r’,‘l’,‘d’]
最终
[‘h’,‘e’,‘l’,‘o’,‘w’,‘r’,‘d’]
当然存储的顺序也许不是我写的这样,因为HashSet中存储元素是无自然序的

但是我在敲代码时发现了一个问题,如果将new的新对象增添到Set中,元素内容是可以重复添加的
看代码

Student类

public class Students {
 private int age;
 private String name;
 public Students(int age, String name) {
  super();
  this.age = age;
  this.name = name;
  
 }
 public int getAge() {
  return age;
 }
 public String getName() {
  return name;
 }
 @Override
 public String toString() {
  // TODO Auto-generated method stub
  
  return "Student [ name: "+this.getName()+", age: "+this.getAge()+"  ]";
 }
 }

Test程序

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetIntroduction {
 public static void main(String[] args) {
  Set<Students> container = new HashSet<>();
  container.add(new Students(18, "Jim"));
  container.add(new Students(19, "Jone"));
  container.add(new Students(18, "Alex"));
  container.add(new Students(18, "Jim"));
  Iterator<Students> itr = container.iterator();
  while(itr.hasNext()) {
   System.out.println(itr.next());
  }
 }
 }

当时我就很懵,Set不是不能增添相同的元素吗,后来才发现 HashSet是以equal与hashcode进行比较,所以要重写hashcode与equals

更改后的Student类


public class Students {
 private int age;
 private String name;
 public Students(int age, String name) {
  super();
  this.age = age;
  this.name = name;
  
 }
 public int getAge() {
  return age;
 }
 public String getName() {
  return name;
 }
 @Override
 public String toString() {
  // TODO Auto-generated method stub
  
  return "Student [ name: "+this.getName()+", age: "+this.getAge()+"  ]";
 }
@Override
 public boolean equals(Object obj) {
  if(this == obj) {
   return true;
  }
  if(obj == null) {
   return false;
  }
  if(obj instanceof Students) {
   Students students = (Students) obj;
   if(this.name.equals(students.name)&&this.age == students.age) {
    return true;
   }
  }
  return false;
 }
 @Override
 public int hashCode() {
  // TODO Auto-generated method stub
  
  //第一种转换string的方法
//  String age = String.valueOf(this.age);
  //第二种
//  String age = this.age+"";
  String age = Integer.toString(this.age);
  return age.hashCode()*this.name.hashCode();
 }
 }

参考Blog(https://www.cnblogs.com/interdrp/p/12324738.html)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值