Guest User

Untitled

a guest
Jun 17th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. package vererbungUndGenerizitaet.relationen;
  2. import java.util.HashMap;
  3. import java.util.HashSet;
  4. import java.util.Map;
  5. import java.util.Set;
  6. public class BinaryRelation<T, U> {
  7. private Map<T, Set<U>> relatedTo = new HashMap<T, Set<U>>();
  8. public BinaryRelation() {
  9. }
  10. public void add(T x, U y) {
  11. Set<U> relations = relatedTo.get(x);
  12. // if there is no relation for left element yet
  13. if (relations == null) {
  14. relations = new HashSet<U>();
  15. relatedTo.put(x, relations);
  16. }
  17. relations.add(y);
  18. }
  19. public Set<U> getRelations(T x) {
  20. Set<U> relations = relatedTo.get(x);
  21. return java.util.Collections
  22. .unmodifiableSet(relations == null ? new HashSet<U>()
  23. : relations);
  24. }
  25. public Set<T> getElements() {
  26. return relatedTo.keySet();
  27. }
  28. public boolean isRelated(T x, U y) {
  29. return getRelations(x).contains(y);
  30. }
  31. @Override
  32. public String toString() {
  33. StringBuilder build = new StringBuilder();
  34. build.append("[");
  35. for (T x : getElements()) {
  36. for (U y : getRelations(x)) {
  37. build.append("(");
  38. build.append(x);
  39. build.append(", ");
  40. build.append(y);
  41. build.append("),");
  42. }
  43. }
  44. if (build.length() > 1)
  45. build.replace(build.length() - 1, build.length(), "");
  46. build.append("]");
  47. return build.toString();
  48. }
  49. public static void main(String[] args) {
  50. BinaryRelation<String, Integer> rel = new BinaryRelation<String, Integer>();
  51. rel.add("eins", 1);
  52. rel.add("eins", 2);
  53. rel.add("eins", 3);
  54. rel.add("zwei", 1);
  55. rel.add("drei", 1);
  56. rel.add("zwei", 3);
  57. System.out.println(rel);
  58. }}
Add Comment
Please, Sign In to add comment