见代码:import java.util.ArrayList;
import actor.Sheep;public class BoundedGrid<E>
{
private Object[][] occupantArray; // the array storing the grid elements public E get(Location loc)
{
if (!isValid(loc))
throw new IllegalArgumentException("Location " + loc
+ " is not valid");
return (E) occupantArray[loc.getX()][loc.getY()];
} public ArrayList<Location> getEmptyLocations(Location l)
{
ArrayList<Location> theLocations = new ArrayList<Location>(); for (int r = -1; r < 2; r++)
{
for (int c = -1; c < 2; c++)
{
Location loc = new Location(l.getX() + r, l.getY() + c);
if (loc.getX() >=0 && loc.getY() >=0 && get(loc) == null)//get(loc) == null就可以
theLocations.add(loc);
}
}
return theLocations;
} public ArrayList<Location> getSheepLocations(Location l)
{
ArrayList<Location> theLocations = new ArrayList<Location>(); // Look at all grid locations.
for (int r = -1; r < 2; r++)
{
for (int c = -1; c < 2; c++)
{
Location loc = new Location(l.getX() + r, l.getY() + c);
if (loc.getX() >=0 && loc.getY() >=0 && get(loc) == Sheep)
//但是我希望判断loc这个位置是否是Sheep类的对象的时候就不行了,为什么呀?
theLocations.add(loc);
}
}
return theLocations;
}
import actor.Sheep;public class BoundedGrid<E>
{
private Object[][] occupantArray; // the array storing the grid elements public E get(Location loc)
{
if (!isValid(loc))
throw new IllegalArgumentException("Location " + loc
+ " is not valid");
return (E) occupantArray[loc.getX()][loc.getY()];
} public ArrayList<Location> getEmptyLocations(Location l)
{
ArrayList<Location> theLocations = new ArrayList<Location>(); for (int r = -1; r < 2; r++)
{
for (int c = -1; c < 2; c++)
{
Location loc = new Location(l.getX() + r, l.getY() + c);
if (loc.getX() >=0 && loc.getY() >=0 && get(loc) == null)//get(loc) == null就可以
theLocations.add(loc);
}
}
return theLocations;
} public ArrayList<Location> getSheepLocations(Location l)
{
ArrayList<Location> theLocations = new ArrayList<Location>(); // Look at all grid locations.
for (int r = -1; r < 2; r++)
{
for (int c = -1; c < 2; c++)
{
Location loc = new Location(l.getX() + r, l.getY() + c);
if (loc.getX() >=0 && loc.getY() >=0 && get(loc) == Sheep)
//但是我希望判断loc这个位置是否是Sheep类的对象的时候就不行了,为什么呀?
theLocations.add(loc);
}
}
return theLocations;
}
判断是否为哪个类用 instanceof 关键字