Why does this error occur
The code is formally correct. You can apply almost any object to any other object, and the code will be compiled. If the cast is not valid, a ClassCastException runtime will be ClassCastException .
Your IDE may detect insecure snooping and complain about them during compilation. Or as a warning, or as an error. This is a configuration issue. Obviously, the OPs IDE is configured so that such code smells like a compilation error
Why is this cast unsafe
You can answer your question by answering this:
Can you create a List<MyType> that is not a SpecialList ?
You cannot drop List<MyType> to SpecialList , because there may be objects that will be List<MyType> and really not be SpecialList .
Decision
Change application architecture
There are two things you can do: either use the SpecialList class throughout your code, or use the generic List<MyType> .
In other words, either change:
doStuff(List<MyType> list) to doStuff(SpecialList list)
or change
private List<SpecialList> bigList to private List<List<MyType>> bigList
You must decide whether you want a common list of interfaces or your own class to be used everywhere. Remember that you can alaways cast SpecialList to List<MyType> , because all instances of SpecialList are also instances of List<MyType> . This does not work the other way around.
Make sure the cast is always valid.
If you absolutely want this project to work, use instanceof to check if the list is SpecialList . For instance:
public void doStuff(List<MyType> list) { if (list instanceof SpecialList) { bigList.add((SpecialList)list); } else { SpecialList sl = new SpecialList(list);