41 lines
1.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/Holder.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
import java.util.Objects;
2015-06-15 17:47:35 -07:00
public class Holder<T> {
private T value;
public Holder() {}
public Holder(T val) { value = val; }
public void set(T val) { value = val; }
public T get() { return value; }
@Override public boolean equals(Object o) {
return o instanceof Holder &&
Objects.equals(value, ((Holder)o).value);
}
@Override public int hashCode() {
2017-01-10 14:11:16 -08:00
return Objects.hashCode(value);
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
Holder<Apple> apple = new Holder<>(new Apple());
Apple d = apple.get();
apple.set(d);
// Holder<Fruit> Fruit = apple; // Cannot upcast
Holder<? extends Fruit> fruit = apple; // OK
2015-06-15 17:47:35 -07:00
Fruit p = fruit.get();
d = (Apple)fruit.get(); // Returns 'Object'
try {
Orange c = (Orange)fruit.get(); // No warning
} catch(Exception e) { System.out.println(e); }
// fruit.set(new Apple()); // Cannot call set()
// fruit.set(new Fruit()); // Cannot call set()
System.out.println(fruit.equals(d)); // OK
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
java.lang.ClassCastException: Apple cannot be cast to
Orange
false
2015-09-07 11:44:36 -06:00
*/