Created
March 7, 2017 14:42
-
-
Save cbmeeks/f4efb4fefc3a9ef6ec2f4ef6e24b3079 to your computer and use it in GitHub Desktop.
Java Sets Unique?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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