Since the method is named insertEvil
, the point of this exercise is probably to teach you that it is possible to insert the "wrong" type of object to a ArrayList<T>
, and that generics are not actually enforced at runtime. See: type erasure.
In this case, you need to insert a String
into a ArrayList<Integer>
.
One way to do it is to cast it to a raw type:
((ArrayList)intList).add("Hello World");
However, this doesn't actually cause your code to print "OK", because the call to intList.get
would attempt to cast the string you inserted back to an Integer
, because intList
is declared to be an ArrayList<Integer>
. The cast will fail at runtime.
To get this to work, you need intList
to be a ArrayList
or ArrayList<String>
, so the call to get
wouldn't try to cast the string to Integer
.
If you are only allowed to change the code between the two comments, the only ways I can think of are dirty tricks like declaring a new method. You can still declare a new method by just changing the lines between the two comments.
For example, if the code between the two comments are replaced with:
helper(intList);
}
static void helper(ArrayList intList) {
intList.add("Hello World");
Then it becomes:
static void insertEvil() {
var intList = new ArrayList<Integer>();
// Change starts here
helper(intList);
}
static void helper(ArrayList intList) {
intList.add("Hello World");
// Change ends here
if (intList.get(0).equals("Hello World")) {
System.out.println("Ok");
} else {
System.out.println("Failure");
}
}
The idea is to pass intList
to another method, to change what intList
means in the get
call. In the above code, intList
in the get
call now refers to the method parameter, instead of the variable declared in insertEvil
.
That said, I think it is highly likely that the intended solution is just ((ArrayList)intList).add("Hello World");
. Whoever designed this might not have considered that get
would cast the element back to an Integer
. (I nearly missed it too!)