4

I've got a LinkedHashMap that contains an object at key and one at value.

I've used the code

yourShots.keySet().toArray()[yourShots.size()-1]

to return the last object of the keys. However, I am unable to access a method that the object has.

I've used the getClass() method to determine that I do indeed have the right kind of object, but the method cannot be called. I simply get the error that the method cannot be found.

Am I doing something wrong?

Brian
  • 119
  • 6

3 Answers3

9

toArray give you generic Object type. You have to cast it to your key class before using it.

KeyClass key = (KeyClass) yourShots.keySet().toArray()[yourShots.size()-1];
// Here you can access your desired method

Edit:

As @rgettman suggest, you could use the overloaded version toArray(T[]) to avoid the cast. In this case you should provide an initialized array with size of keySet() beforehand.

Mạnh Quyết Nguyễn
  • 15,590
  • 1
  • 17
  • 41
  • 1
    Or you can use the overload [`Set.toArray(T[])`](https://docs.oracle.com/javase/9/docs/api/java/util/Set.html#toArray-T:A-) to avoid the cast. – rgettman May 03 '18 at 18:34
3

Alternatively you can use an Iterator to avoid copying all the unwanted keys to an array just to throw it away afterwards. It also saves the cast due to being generic.

Key key = null;
for(Iterator<Key> iterator = yourShots.keySet().iterator(); iterator.hasNext();) {
    key = iterator.next();
}
Izruo
  • 1,678
  • 7
  • 19
1

Edit:
You can convert your keySet into a List and then get the last object.
Something like this:

List<Key> keys = new ArrayList(yourShots.keySet());
Key lastKey = keys.get(keys.size() - 1);

Original Post
You're accessing the wrong method.

yourShots.keySet() returns a Set containing all keys in your Map.

in order to access the last value in your map, you need to call: yourShots.values()

Hope this helps

S1LENT WARRIOR
  • 10,609
  • 4
  • 39
  • 55