LoganBlackisle

generics opg 4, original

Nov 28th, 2019
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package setoperationsopgave;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. public class SetOperations {
  7.  
  8.     public static <T> Set<T> union(Set<T> s1, Set<T> s2) {
  9.         Set<T> result = new HashSet<T>(s1);
  10.         result.addAll(s2);
  11.         return result;
  12.     }
  13.  
  14.     public static <T> Set<T> differens(Set<T> s1, Set<T> s2) {
  15.         Set<T> copy = new HashSet<T>();
  16.         for (T t : s1) {
  17.             if (!s2.contains(t)) {
  18.                 copy.add(t);
  19.             }
  20.         }
  21.         return copy;
  22.     }
  23.  
  24.     public static <T> Set<T> intesection(Set<T> s1, Set<T> s2) {
  25.         Set<T> copy = new HashSet<T>();
  26.         for (T t : s1) {
  27.             if (s2.contains(t)) {
  28.                 copy.add(t);
  29.             }
  30.         }
  31.         return copy;
  32.     }
  33. }
  34.  
  35.  
  36.  
  37.  
  38.  
  39. package setoperationsopgave;
  40.  
  41. import java.util.HashSet;
  42. import java.util.Set;
  43.  
  44. public class AfproevSetOperations {
  45.  
  46.     public static void main(String[] args) {
  47.         Set<Integer> s1 = new HashSet<Integer>();
  48.         Set<Integer> s2 = new HashSet<Integer>();
  49.  
  50.         for (int i = 1; i <= 10; i++) {
  51.             s1.add(i);
  52.             s2.add(2 * i);
  53.         }
  54.         System.out.println("Mængde1:   " + s1);
  55.         System.out.println("Mængde 2:  " + s2);
  56.         System.out.println("Forening:  " + SetOperations.union(s1, s2));
  57.         System.out.println("Differens: " + SetOperations.differens(s1, s2));
  58.         System.out.println("Fælles:    " + SetOperations.intesection(s1, s2));
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment