Brian
Brian

Reputation: 119

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?

Upvotes: 4

Views: 200

Answers (3)

S1LENT WARRIOR
S1LENT WARRIOR

Reputation: 12214

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

Upvotes: 1

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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.

Upvotes: 9

Izruo
Izruo

Reputation: 2276

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();
}

Upvotes: 3

Related Questions