What will be the output of the following program? and Why?

class KahveDukkani {

  public static void main(String[] args) {
    List strings = new ArrayList();
    tehlikeliEkleme(strings, new Integer(42));
    String s = strings.get(0);
    System.out.println(s);
  }

  private static void tehlikeliEkleme(List list, Object o) {
    list.add(o);
  }

}

 

If you run the above program you will get ClassCastException in runtime because we are trying to convert Integer object into String. In order to prevent this error, you have 2 options

1 – Don’t try to convert Integer into String (not make sense)
2 – Use Generics.

 

class KahveDukkani {

  public static void main(String[] args) {
    List strings = new ArrayList();
    tehlikeliEkleme(strings, new Integer(42));
    String s = strings.get(0);
    System.out.println(s);
  }

  private static <E> void tehlikeliEkleme(List<E> list, E o) {
     list.add(o);
  }
}

In this version, you will get the error in compile time which is very valuable because you have time to fix the error.

No Comments

Post a Comment

Comment
Name
Email
Website