Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package vererbungUndGenerizitaet.relationen;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Map;
- import java.util.Set;
- public class BinaryRelation<T, U> {
- private Map<T, Set<U>> relatedTo = new HashMap<T, Set<U>>();
- public BinaryRelation() {
- }
- public void add(T x, U y) {
- Set<U> relations = relatedTo.get(x);
- // if there is no relation for left element yet
- if (relations == null) {
- relations = new HashSet<U>();
- relatedTo.put(x, relations);
- }
- relations.add(y);
- }
- public Set<U> getRelations(T x) {
- Set<U> relations = relatedTo.get(x);
- return java.util.Collections
- .unmodifiableSet(relations == null ? new HashSet<U>()
- : relations);
- }
- public Set<T> getElements() {
- return relatedTo.keySet();
- }
- public boolean isRelated(T x, U y) {
- return getRelations(x).contains(y);
- }
- @Override
- public String toString() {
- StringBuilder build = new StringBuilder();
- build.append("[");
- for (T x : getElements()) {
- for (U y : getRelations(x)) {
- build.append("(");
- build.append(x);
- build.append(", ");
- build.append(y);
- build.append("),");
- }
- }
- if (build.length() > 1)
- build.replace(build.length() - 1, build.length(), "");
- build.append("]");
- return build.toString();
- }
- public static void main(String[] args) {
- BinaryRelation<String, Integer> rel = new BinaryRelation<String, Integer>();
- rel.add("eins", 1);
- rel.add("eins", 2);
- rel.add("eins", 3);
- rel.add("zwei", 1);
- rel.add("drei", 1);
- rel.add("zwei", 3);
- System.out.println(rel);
- }}
Add Comment
Please, Sign In to add comment