MCPcopy Index your code
hub / github.com/BruceEckel/OnJava8-Examples / Holder

Class Holder

generics/Holder.java:7–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5import java.util.Objects;
6
7public class Holder<T> {
8 private T value;
9 public Holder() {}
10 public Holder(T val) { value = val; }
11 public void set(T val) { value = val; }
12 public T get() { return value; }
13 @Override public boolean equals(Object o) {
14 return o instanceof Holder &&
15 Objects.equals(value, ((Holder)o).value);
16 }
17 @Override public int hashCode() {
18 return Objects.hashCode(value);
19 }
20 public static void main(String[] args) {
21 Holder<Apple> apple = new Holder<>(new Apple());
22 Apple d = apple.get();
23 apple.set(d);
24 // Holder<Fruit> Fruit = apple; // Cannot upcast
25 Holder<? extends Fruit> fruit = apple; // OK
26 Fruit p = fruit.get();
27 d = (Apple)fruit.get(); // Returns 'Object'
28 try {
29 Orange c = (Orange)fruit.get(); // No warning
30 } catch(Exception e) { System.out.println(e); }
31 // fruit.set(new Apple()); // Cannot call set()
32 // fruit.set(new Fruit()); // Cannot call set()
33 System.out.println(fruit.equals(d)); // OK
34 }
35}
36/* Output:
37java.lang.ClassCastException: Apple cannot be cast to
38Orange

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected