About Question enthuware.ocajp.i.v7.2.850 :
Posted: Mon Dec 02, 2013 4:41 pm
You must specify the class of objects you want to store in ArrayList when you declare a variable of type ArrayList.
This is not true because you can still use non-generic form. For example, instead of using ArrayList<String> listOfStrings; you can use: ArrayList listOfStrings; Of course, if you use non generic version, you will lose the compile time type checking.
Is this illustrated b y the following
import java.util.ArrayList;
class LearnJava{
public static void main(String args[]){
ArrayList<String> al = new ArrayList<>();
al.add("0");
a1.add(1);
ArrayList al2 = new ArrayList();
al2.add("0");
al2.add(1);
for(Object i : al2){
System.out.println(i);
}
}
}
a1.add(1); gives a compile error because I declared the ArrayList to contain Strings and 1 is an integer. Compiler is making sure I add what I specified.
Since I do not specify the type of element al2 can contain I have to use a loopvariable of type Object in for(Object i : al2) and therefore lose the item-specific functions since loopvariable i is of type Object instead of e.g. String?
This is not true because you can still use non-generic form. For example, instead of using ArrayList<String> listOfStrings; you can use: ArrayList listOfStrings; Of course, if you use non generic version, you will lose the compile time type checking.
Is this illustrated b y the following
import java.util.ArrayList;
class LearnJava{
public static void main(String args[]){
ArrayList<String> al = new ArrayList<>();
al.add("0");
a1.add(1);
ArrayList al2 = new ArrayList();
al2.add("0");
al2.add(1);
for(Object i : al2){
System.out.println(i);
}
}
}
a1.add(1); gives a compile error because I declared the ArrayList to contain Strings and 1 is an integer. Compiler is making sure I add what I specified.
Since I do not specify the type of element al2 can contain I have to use a loopvariable of type Object in for(Object i : al2) and therefore lose the item-specific functions since loopvariable i is of type Object instead of e.g. String?