Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. package a;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6.  
  7. public class Main {
  8.  
  9.     public static void main(String[] args) {
  10.  
  11.         Set<String> uniqueStrings = new HashSet<>();
  12.         uniqueStrings.add("Hi");
  13.         uniqueStrings.add("Hi");
  14.         System.out.println(uniqueStrings.size()); // დაბეჭდავს 1-ს
  15.  
  16.         Set<AnyObject> uniqueObjects = new HashSet<>();
  17.         AnyObject a = new AnyObject("foo", 1);
  18.         AnyObject b = new AnyObject("foo", 1);
  19.         uniqueObjects.add(a);
  20.         uniqueObjects.add(b);
  21.  
  22.         System.out.println(uniqueObjects.size()); // დაბეჭდავს 1-ს
  23.  
  24.         AnyObject c = new AnyObject("foo", 2);
  25.         uniqueObjects.add(c);
  26.  
  27.         System.out.println(uniqueObjects.size()); // დაბეჭდავს 2-ს
  28.  
  29.         AnyObject[] array = uniqueObjects.toArray(new AnyObject[uniqueObjects
  30.                 .size()]);
  31.         System.out.println(Arrays.toString(array)); // საბოლოო მასივი უნიკალური
  32.                                                     // ელემენტებით
  33.     }
  34.  
  35.     static class AnyObject {
  36.         private String foo;
  37.         private int bar;
  38.  
  39.         public AnyObject(String foo, int bar) {
  40.             super();
  41.             this.foo = foo;
  42.             this.bar = bar;
  43.         }
  44.  
  45.         @Override
  46.         public int hashCode() {
  47.             // საჭიროა ჰეშკოდის გადაფარვაც
  48.             return bar;
  49.         }
  50.  
  51.         @Override
  52.         public boolean equals(Object obj) {
  53.             if (!(obj instanceof AnyObject)) {
  54.                 return false;
  55.             }
  56.             // აქ უნდა გადაწყვიტო რას ნიშნავს ორი AnyObject-ის ეგზემპლარის
  57.             // ტოლობა
  58.             // სიმარტივისთვის შევადაროთ მარტო bar ველები
  59.             return ((AnyObject) obj).bar == bar;
  60.         }
  61.  
  62.         @Override
  63.         public String toString() {
  64.             return "AnyObject [foo=" + foo + ", bar=" + bar + "]";
  65.         }
  66.  
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement