FAQ Database Discussion Community


Java Generics Puzzler, extending a class and using wildcards

java,generics,bounded-wildcard
I've been beating my head against this one for awhile and thought that maybe some fresh eyes will see the issue; thanks for your time. import java.util.*; class Tbin<T> extends ArrayList<T> {} class TbinList<T> extends ArrayList<Tbin<T>> {} class Base {} class Derived extends Base {} public class Test { public...

Java 8 generic collections with optionals

java,generics,java-8,optional,bounded-wildcard
I have a relatively simple looking problem that I am trying to solve. There doesn't seem to be an intuitive way to do this or, I am missing something here. Consider this method to find the main image and if none exists, return first image- public Image findMainImage(Collection<? extends Image>...

java.lang.Class generics and wildcards

java,generics,bounded-wildcard
Why is is that the following code does not compile? interface Iface<T> { } class Impl<T> implements Iface<T> { } class TestCase { static Class<? extends Iface<?>> clazz = Impl.class; } The error is java: incompatible types: java.lang.Class<Impl> cannot be converted to java.lang.Class<? extends Iface<?>> but I don't see why...

Problems with inferring types with bounded wildcards

java,generics,bounded-wildcard
What's the proper way of setting temp2.in in the below snippet? Why does the code not compile? public class WildCards { public static void main(String[] args) { TheBox<Integer> temp1 = new TheBox<Integer>(); temp1.set(10); TheBox<? extends Number> temp2 = temp1; temp2.set(1); } public static class TheBox<T> { T in; public T...

In Java, what can a wild card do that regular generics cannot do?

java,generics,bounded-wildcard,unbounded-wildcard
I am new to Java. In this document they give this as a use case for using wildcard: static void printCollection(Collection c) { Iterator i = c.iterator(); for (int k = 0; k < c.size(); k++) { System.out.println(i.next()); } } This is their solution: static void printCollection(Collection<?> c) { for...

How do I make a list of several kind of object if I cannot use wildcards?

java,bounded-wildcard,java-generics
I want to make a List which can hold two kind of Object. What comes in my mind is to use wildcard. Below is my code. public class Parent { //code } public class ChildOne extends Parent { //code } public class ChildTwo extends Parent { //code } public class...

Where does the Java spec say List assigns to List?

java,generics,bounded-wildcard,subtyping
Assume class B inherits from class A. The following is legal Java: List<A> x; List<? super B> y = x; In terms of the specification, this means that List<A> assignsTo List<? super B>. However, I am having trouble finding the part of the spec that says this is legal. In...