Advertisement
binibiningtinamoran

Box (Generics)

May 27th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.79 KB | None | 0 0
  1. public class Box<T> {
  2.    
  3.     private T thing;
  4.     private int thingCount;
  5.    
  6.     public Box(T firstThing) {
  7.         this.thing = firstThing;
  8.         this.thingCount = 1;
  9.     }
  10.    
  11.     public T getContents() {
  12.         return thing;
  13.     }
  14.     public int getCount() {
  15.         return thingCount;
  16.     }
  17.    
  18.     public void replaceContents(T newThing) {
  19.         this.thing = newThing;
  20.         thingCount++;
  21.     }
  22.    
  23.     @Override
  24.     public String toString() {
  25.         return thing.toString() + " (item " + thingCount + ")";
  26.     }
  27.    
  28.     @Override
  29.     public boolean equals(Object other) {
  30.         if(other instanceof Box<?>) {
  31.             Box<?> otherBoxR = (Box<?>) other;
  32.            
  33.             boolean sameThing = this.thing.equals(otherBoxR.thing);
  34.             boolean sameCount = this.thingCount==otherBoxR.thingCount;
  35.            
  36.             return sameThing && sameCount;
  37.            
  38.         } else {
  39.             return false;
  40.         }
  41.     }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement