HashSet的元素是否可被修改

来源:互联网 发布:嵌入式软件 启动过程 编辑:程序博客网 时间:2024/06/05 00:08
import java.util.HashSet;public class main {    private static class Test {        int x = 0;        public int getX() {            return x;        }        public void setX(int x) {            this.x = x;        }        @Override        public boolean equals(Object o) {            if (this == o) return true;            if (o == null || getClass() != o.getClass()) return false;            Test test = (Test) o;            return x == test.x;        }        @Override        public int hashCode() {            return x;        }    }    public static void main(String[] args) {        Test test = new Test();        HashSet<Test> set = new HashSet<>();        set.add(test);        System.out.println(set.contains(test)); // true        System.out.println(test.hashCode()); // 0        test.setX(100);        System.out.println(set.contains(test)); // false 修改后set中的hashcode不变,对象的hashcode改变        System.out.println(test.hashCode()); // 100        System.out.println(set.size()); // 1    }}

这我认为应当分两种情况考虑:

  1. 没有重写equal和hashcode函数,可修改自定义对象(这里留意是自定义对象),因为hashcode是相当于对象地址的映射或者地址经过一系列的转换得到的值。
  2. 重写了equal和hashcode函数,无法修改自定义对象,如上,在不扩容的情况下,HashSet不会rehash,原有的对象的是无法被找到的,但是若在扩容的情况下,那就另当别论了。
0 0
原创粉丝点击