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?
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With