Question
What will be the result of attempting to compile and run the following code?
class Fruit {}/*from w w w .jav a2 s .c o m*/
class Apple extends Fruit {}
class Orange extends Fruit {}
public class Main {
public static void main(String[] args) {
ArrayList<Apple> aList = new ArrayList<Apple>();
aList.add(new Apple());
ArrayList bList = aList; // (1)
ArrayList<Orange> oList = bList; // (2)
oList.add(new Orange());
System.out.println(aList);
}
}
Select the one correct answer.
- (a) The code will fail to compile because of errors in (1) and (2).
- (b) The code will fail to compile because of an error in (1).
- (c) The code will fail to compile because of an error in (2).
- (d) The code will compile with an unchecked warning in both (1) and (2).
- (e) The code will compile with an unchecked warning in (1).
- (f) The code will compile with an unchecked warning in (2).
- (g) The code will compile without warnings, but throw a ClassCastException at runtime in (2).
- (h) The code will compile without warnings and will print "[Apple@hash-code, Orange@hash-code]", when run.
(f)
Note
Assigning bList
, a reference of a non-generic list, to oList
, a reference of a generic list, in (2) results in an unchecked conversion warning.
PreviousNextRelated