这可以按预期工作(注意equals
和hashCode
on Concept
)
package com.stackoverflow.so19634761;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Set;
public class ISect {
public static void main(final String[] args) {
final Concept a = new Concept("Dog");
final Concept b = new Concept("Tree");
final Concept c= new Concept("Dog");
final Set<Concept> set1 = Sets.newHashSet(a);
final Set<Concept> set2 = Sets.newHashSet(b, c);
final SetView<Concept> inter = Sets.intersection(set1, set2);
System.out.println(inter); // => [Concept [data=Dog]]
}
private static class Concept {
private final String data;
// below this point code was generated by eclipse.
public String getData() {
return data;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Concept other = (Concept) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
public Concept(String data) {
this.data = data;
}
@Override
public String toString() {
return "Concept [data=" + data + "]";
}
}
}