I have written the following program using an ArrayList.
import java.util.ArrayList;
publicclass TestArrayList {
publicstaticvoid main(String[] args) {
//create a list to store cities
ArrayList cityList = new ArrayList();
//add some cities to the list
cityList.add("London");
//citylist now contains [London]
cityList.add("Denver");
cityList.add("Paris");
cityList.add("Timbuktu");
cityList.add("Burlington");
cityList.add("Dublin");
cityList.add("Miami");
cityList.add("Tokyo");
//cityList now contains[London,Denver,Paris,Timbuktu,Burlington, Dublin,Miami,Tokyo]
System.out.println("list size " + cityList.size());
System.out.println("is miami in the list? " + cityList.contains("Miami"));
System.out.println("location of denver in the list " + cityList.indexOf("Denver"));
System.out.println("Is the list empty " + cityList.isEmpty());
//insert new city at index 2
cityList.add(2, "Xian");
//remove a city from the list
cityList.remove("Miami");
//remove city at index 1
cityList.remove(1);
//display contents in the list
System.out.println(cityList.toString());
//display contents in reverse order
for (int i = 0; i < cityList.size(); i++) {
System.out.println(cityList.get(i) + " ");
}
//create a list to store two circle
ArrayList list = new ArrayList();
//add two circles
list.add(new Circle4(2));
list.add(new Circle4(3));
//display area of first circle in list
System.out.println("\nthe area of the circle? " + ((Circle4)list.get(0)).getArea());
}
}
When I try to compile, I have "unchecked or unsafe operations." I compiled it with the suggested -Xlint:unchecked parameter, and there are 11 errors: on all of the <ArrayList>.add(<item>).Does anyone know what I need to change, or what I'm doing wrong?
TestArrayList.java:43: cannot find symbol symbol : class Circle4
So I reduced it down:
import java.util.ArrayList;
publicclass TestArrayList {
publicstaticvoid main(String[] args) {
//create a list to store cities
ArrayList cityList = new ArrayList();
//add some cities to the list
cityList.add("London");
}
}
The modified code still creates the "Unchecked or unsafe operations" error:
$ javac TestArrayList.java -Xlint:unchecked TestArrayList.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList cityList.add("London"); ^ 1 warning
Adding <String> type parameters to the ArrayList declaration fixed it:
import java.util.ArrayList;
publicclass TestArrayList {
publicstaticvoid main(String[] args) {
//create a list to store cities
ArrayList<String> cityList = new ArrayList<String>();
//add some cities to the list
cityList.add("London");
}
}