Skip to content

Instantly share code, notes, and snippets.

@cbmeeks
Created March 7, 2017 14:42
Show Gist options
  • Save cbmeeks/f4efb4fefc3a9ef6ec2f4ef6e24b3079 to your computer and use it in GitHub Desktop.
Save cbmeeks/f4efb4fefc3a9ef6ec2f4ef6e24b3079 to your computer and use it in GitHub Desktop.
Java Sets Unique?
package com.company;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static class Test {
private String blah;
public Test(String blah) {
this.blah = blah;
}
@Override
public String toString() {
return "Test{" + "blah='" + blah + '\'' + '}';
}
public String getBlah() {
return blah;
}
public void setBlah(String blah) {
this.blah = blah;
}
}
public static void main(String[] args) {
Set<Test> set = new HashSet<>();
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
for (Test test : set) {
System.out.println(test);
}
}
}
// OUTPUT:
Test{blah='ABC'}
Test{blah='ABC'}
Test{blah='ABC'}
Test{blah='ABC'}
Test{blah='ABC'}
Test{blah='ABC'}
package com.company;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static class Test {
private String blah;
public Test(String blah) {
this.blah = blah;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Test test = (Test) o;
return blah.equals(test.blah);
}
@Override
public int hashCode() {
return blah.hashCode();
}
@Override
public String toString() {
return "Test{" + "blah='" + blah + '\'' + '}';
}
public String getBlah() {
return blah;
}
public void setBlah(String blah) {
this.blah = blah;
}
}
public static void main(String[] args) {
Set<Test> set = new HashSet<>();
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
set.add(new Test("ABC"));
for (Test test : set) {
System.out.println(test);
}
}
}
// OUTPUT:
Test{blah='ABC'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment