I tried to understand next thing. This block code will print next
example.TestGenerics$One@49c2faae
example.TestGenerics$Two@20ad9418
So I suppose that cast was complete successfully, but I expect ClassCastException for second object in list.
public class TestGenerics
{
public static void main(String[] args)
{
Generic<One> integerGeneric = new Generic<One>(new Container(Lists.<Object>newArrayList(new One(), new Two())));
integerGeneric.checkContainer();
}
static class Generic<T>
{
private Container container;
public Generic(Container container)
{
this.container = container;
}
public void checkContainer()
{
for (Object key : container.getObjects())
{
final T genericKey = (T)key;
System.out.println(genericKey);
}
}
}
static class Container
{
Iterable<Object> objects;
public Container(Iterable<Object> objects)
{
this.objects = objects;
}
public Iterable<Object> getObjects()
{
return objects;
}
}
static class One
{
}
static class Two
{
}
}
P.S. Also I faced a problem that generic type cast (using (T)object) returns null instead of throwing exception ClassCastExceptiong, but i cant reproduce it. If anyone know about this, comment here, please