Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accesing a method in the last object in a LinkedHashMap

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?

like image 907
Brian Avatar asked Dec 11 '22 06:12

Brian


2 Answers

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.

like image 177
Mạnh Quyết Nguyễn Avatar answered Dec 20 '22 03:12

Mạnh Quyết Nguyễn


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();
}
like image 28
Izruo Avatar answered Dec 20 '22 01:12

Izruo