fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Box<T> {
  9. private T element;
  10.  
  11. public T getElement() {
  12. return element;
  13. }
  14.  
  15. public void setElement(T element) {
  16. this.element = element;
  17. }
  18. }
  19.  
  20. class Ideone
  21. {
  22. public static void main (String[] args) throws java.lang.Exception
  23. {
  24. List<Box> l = new ArrayList<>(); //Just List of Box with no specific type
  25. Box<String> box1 = new Box<>();
  26. box1.setElement("aa");
  27. Box<Integer> box2 = new Box<>();
  28. box2.setElement(10);
  29.  
  30. l.add(box1);
  31. l.add(box2);
  32.  
  33. //Case 1
  34. Box<Integer> b1 = l.get(0);
  35. System.out.println(b1.getElement()); //why no error
  36.  
  37. //Case 2
  38. Box<String> b2 = l.get(1);
  39. System.out.println(b2.getElement()); //throws ClassCastException
  40. }
  41. }
Runtime error #stdin #stdout #stderr 0.11s 320576KB
stdin
Standard input is empty
stdout
aa
stderr
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at Ideone.main(Main.java:39)