Skip to content
Search

Java.util.HashSet

lastmod 2020-09-09created 2020-09-091 edits

Notes on HashSet, a Set (unordered, no duplicate insertion) with an added hash (Hash) function.

Simple usage

Simple usage is as follows.

HashSet<String> hs = new HashSet<>();
hs.add("주원?병준");
hs.add("몽골용단");
hs.add("안피곤인애");
hs.add("안피곤인애");
System.out.println(hs);

HashSet<Student> hs2 = new HashSet<>();
hs2.add(new Student("주원병준", 174, 95));
hs2.add(new Student("몽골용단", 174, 99));
hs2.add(new Student("멋쟁이완샘", 184, 1000));
hs2.add(new Student("멋쟁이완샘", 184, 1000));
System.out.println(hs2);

Custom HashSet

To customize a HashSet, you must override the hashCode() and equals() methods.

@Override
public int hashCode() {
    return name.hashCode();
}

@Override
public boolean equals(Object obj) {
    if(!(obj instanceof Student)) {
        return false;
    }
    Student s = (Student)obj;
    return name.equals(s.name);
}

See also

author Zer0 sitemap