I am new to generics, and I came across this experiment.
import java.util.List;
import java.util.ArrayList;
public class Main {
private static void addIntegerToNames(List listOfNames, Integer i) {
listOfNames.add(i);
}
public static void main(String[] args) {
List<String> Names = new ArrayList<String>();
Names.add("stackOverFlow");
addIntegerToNames(Names, 100);
System.out.println(Names);
}
}
Output : [stackOverFlow, 100]
The compiler does not throw an error while adding an integer to listOfNames because it sees that listOfNames is a list of objects. When this goes at runtime, it still doesn't throw an error, My assumption is that at runtime, "Names" is a List of Objects, because generics are only implemented at compile time.
I have two follow up questions.
- Is my assumption correct?
- Why did java not implemented generics strictly both at compile time and runtime ? Does the current implementation of generics not make Java more error-prone? Was it a tradeoff between performance and safety?