Could you please explain to me what happens here and why it works without errors.
List list = new ArrayList<String>();
list.add(1);
I'm sorry, if there already were similar questions, I failed to properly formulate the question so can't google it
Could you please explain to me what happens here and why it works without errors.
List list = new ArrayList<String>();
list.add(1);
I'm sorry, if there already were similar questions, I failed to properly formulate the question so can't google it
What happens here exposes the weakness of type erasure, the mechanism behind Java generics. The implementation of ArrayList does not change when you change its generic type parameter: it's always java.lang.Object behind the scene.
Since you did not give a type parameter to the interface when declaring your list, compiler allows you to add objects of any type, not only Strings. In particular, int gets autoboxed into java.lang.Integer, so the value of 1 can be added to your list.
Using the raw type List list is approximately equivalent to using List<Object> without type checking. This type of List will accept any type of object. The statement
list.add(1);
autoboxes an Integer to add to the List
Generics of the reference is important. So
List list = new ArrayList<String>();
makes no sense. It must be
List<String> list = new ArrayList<String>();
If you don not provide at generics for the reference type(not the actual object type) it is taken to be as Object. So you can add anything to it.
Also generics is a compile time phenomenon. So when you say how it works it means how your code is compiling without compilation errors. It is for a simple reason that no generics associated with the reference Object and hence is taken as Object(default).
Could you please explain me what happens here and why it works without errors.
Java generics exist only at compile time. If you try to shove an int into something that is only declared as List, (which is bound to Objects by default) at runtime, it will work just fine.
Sure. if you're familiar with C++, generics are kinda like templates (with few exception, but lets not dig that detail). The main idea of Generics is for type safety in your code and hence clarity. This is great for static typed languages like Java. List is an interface and Arraylist extends from it. Hence its a parent (super class) is List. List has features like sublist, etc.
list.add(1) simply calls the add method of the list interface (which is overridden in Arraylist) to add that element to the array.
Also use:
List<String> list = new ArrayList<String>
great article on generics here: http://docs.oracle.com/javase/tutorial/java/generics/