Does an ArrayList allow elements of different types ? If not, Why the following code works
List list1 = new ArrayList<>();
list1.add(1);
list1.add("1");
More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know.
Q1. Does an ArrayList allow elements of different types ? If not, Why the following code works
List list1 = new ArrayList<>();
list1.add(1);
list1.add("1");
Ans. With Java 7 or Later.
If you don't declare the list to be of specific type , it treats it as list of objects.
int 1 is auto boxed to Integer and "1" is String and hence both are objects.
Help us improve. Please let us know the company, where you were asked this question :