diff --git a/jlh/src/main/java/com/jlh/viewer/HashSetTestList.java b/jlh/src/main/java/com/jlh/viewer/HashSetTestList.java new file mode 100644 index 0000000000000000000000000000000000000000..5a706d970e8986ccb8c4b95b4be5550ac3332ae2 --- /dev/null +++ b/jlh/src/main/java/com/jlh/viewer/HashSetTestList.java @@ -0,0 +1,71 @@ +package com.jlh.viewer; + +import java.util.HashSet; + +/** + * Created by jlh + * On 2017/3/9 0009. + */ +public class HashSetTestList { + public static void main(String[] args) { + //通过hashmap 来实现,所以基本上和hashmap差不多 ,,每次add的时候其实就是调用了hashmap.put("key",PERCENT) PERCENT 是一个静态Object对象用于标识这个Key存在了 + HashSet hashSet = new HashSet<>(); + //hashset 判断key是否存在的标准是 equal 和hashcode 的相等与否 缺一不可 + // 因为hashmap找bucket的时候需要hash 然后找到bucket的时候找entry需要equal 所以两者都要 + hashSet.add(new Tuple("jlh","123")); + hashSet.add(new Tuple("jlh","123")); + hashSet.stream().forEach(System.out::println); + } + + public static class Tuple{ + private String name; + private String address; + + public Tuple(String name, String address) { + this.name = name; + this.address = address; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Tuple tuple = (Tuple) o; + + if (name != null ? !name.equals(tuple.name) : tuple.name != null) return false; + return address != null ? address.equals(tuple.address) : tuple.address == null; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (address != null ? address.hashCode() : 0); + return result; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "Tuple{" + + "name='" + name + '\'' + + ", address='" + address + '\'' + + '}'; + } + } +}