For an assignment, I have to create and manipulate a generic object arraylist MyArrayList<E>
extended from java.util.ArrayList<E>
. I need to access a variable highScore
inside the object GameEntry
for the purpose of adding the entry into a MyArrayList
if it meets the requirements, but I can't seem to do it?
GameEntry class
public class GameEntry
{ public String name;
public int highScore;
public String handle;
public GameEntry()
{ name = this.name;
highScore = this.highScore;
handle = this.handle;
}
public GameEntry(String n, int hs, String h)
{ name = n;
highScore = hs;
handle = h;
}
public String getName() { return name; }
public int getHScore() { return highScore; }
public String getHandle() { return handle; }
public String toString() {
return "(" + handle + ", " + name + ": " + highScore + ")";
}
}
MyArrayList class
public class MyArrayList<E> extends java.util.ArrayList<E>
{ private int numEntries = 0;
public MyArrayList() { super(); }
public MyArrayList(int capacity) { super(capacity); }
public boolean isListEmpty() { return this.isEmpty(); }
// add new score to MyArrayList (if it is high enough)
public void addInOrder(GameEntry e) {
int newScore = e.getHScore();
// is the new entry e really a high score?
if(numEntries<this.size() || newScore > this.get(numEntries-1).getHScore())
//ERROR: cannot find symbol - method getHScore()
// ...rest of addInOrder code...
}
}
}
You are getting this error because this.get(numEntries - 1)
will return a generic, and the program will not be able to use getHScore()
with it unless you cast it to GameEntry
.
You can do this by checking to see if it is a GameEntry
object with instanceof
and then casting it:
public void addInOrder(GameEntry e) {
int newScore = e.getHScore();
// is the new entry e really a high score?
if (this.get(numEntries - 1) instanceof GameEntry) {
GameEntry ge = (GameEntry) this.get(numEntries - 1); //Cast to GameEntry
if(numEntries<this.size() || newScore > ge.getHScore()) {
//Do whatever
}
}
//Add behavior for when it is NOT an instance of GameEntry
}
There are probably better ways to implement the behavior you want for addInOrder
, but I thought I'd answer your literal question on why getHScore()
is not working for you correctly.