That's basically my first touch with Java generic types and I can't figure out what is wrong with the following piece of code.
I have a helper class Helper with a static function inRange usng generic type that should return the list of objects from an input list that are in certain range around object at index index (I haven't tested it yet, it's not an issue here if it works correctly or not):
public class Helper {
public static List inRange(List list, int index, int range) {
List res = new ArrayList();
int N = ();
assert(index < N);
if (N == 0)
return res;
int i, j;
/* right range */
i = (index + 1) % N;
j = 0;
while (i != index && j < range) {
((i));
i = (i + 1) % N;
j++;
}
/* left range */
i = (N + index - 1) % N;
j = 0;
while (i != index && j < range && !((i))) {
((i));
i = (N + i - 1) % N;
j++;
}
return res;
}
}
Then I want to use it in a class:
import ;
public class StrategyA extends StrategyB {
public Decision makeDecision(GameView gameView, Action action, View playerView) {
int pos = ().indexOf(playerView);
assert(pos != -1);
ArrayList inRange = ((), pos,
());
// todo ...
return new Decision(.DO_NOTHING, 0);
}
}
where () is of type ArrayList.
Then from my IDE (IntelliJ IDEA) on the line calling inRange(..) I get
Error:(8, 56) java: incompatible types: no instance(s) of type variable(s) T exist so that conforms to
Even I change generic type T directly to View I still get this error
解决方案
Minimize your example like (using Integer of the templated List type):
class Ideone
{
public static void main (String[] args) throws
{
List list = new ArrayList();
ArrayList inRange = (list, 0,1);
}
}
class Helper {
public static List inRange(List list, int index, int range) {
List res = new ArrayList();
return res;
}
}
Then even if you put template types out of the picture:
ArrayList inRange = (list, 0,1);
public static List inRange(List list, int index, int range) { ... }
you see that while the helper static method returns a List, you are trying to assign it to an ArrayList, and that's your problem, as ArrayList is a concrete implementation of List, but you cannot assign a reference to a generic List to a concrete implementation of ArrayList
Just change to:
List inRange = ((), pos,
());