I have this assignment where I'm only allowed to change the signature of the methods. I have a class utility and a test class. Th issue I'm having is that i keep getting argument errors. Here is the Utility Class
public class Utility <T extends Comparable<T>> { //Change this line to create a parameterized class
// Insert your code here
public ArrayList<T> list;
public Utility() {
list = new ArrayList<T>();
}
public Utility (List<T> list) {
this.list = (ArrayList<T>) new ArrayList<>(list);
}
public void mergeList(List<T> list) { //This is the method that the error refers to
for (T obj: this.list)
list.add(obj);
}
}
This is the test that keeps giving me errors
void testMergeList2() {
List<Integer> myList = new ArrayList<Integer>();
myList.add(0);
myList.add(1);
myList.add(2);
myList.add(3);
Utility<Integer> ut = new Utility<Integer>(myList);
List<Number> myList2 = new ArrayList<Number>();
myList2.add(0);
myList2.add(1);
myList2.add(2);
myList2.add(5);
ut.mergeList(myList2); //This is where I get the error
boolean actual = true;
for (int i= 0; i < 4; i ) {
if ((Integer) myList2.get(i) != i || (Integer)myList2.get(i 4)!= i) {
actual = false;
break;
}
}
boolean expected = false;
assertEquals(expected, actual, "mergeList Failed! " expected " expected but " actual " is given");
}
I tried changing T for something else but then the compiler tells me to cast T which I'm not allowed to do since I can't change the body of the method.
CodePudding user response:
Your Utility is declared using Integer
however the myList2
is using Number
. Those are incompatible types.
In order to fix this, change mergeList(List<T> list)
to just mergeList(List list)
. This will work and your test will pass.