开发者

Retrieving keys of a hashmap

开发者 https://www.devze.com 2023-02-14 06:06 出处:网络
Is there any way to retreive the keys of a hashmap other then using keyset? I have written the following code , I have a hashmap named map, it includes integer keys and double values :

Is there any way to retreive the keys of a hashmap other then using keyset? I have written the following code , I have a hashmap named map, it includes integer keys and double values :

    Set<Integer> keys = sorted_map.keySet();
    Object[] weel = new Object[keys.size()];
    Iterator it = keys.iterator();
    int l = 0;
    while(it.hasNext())
    {
        weel[l] = it.next();
    }

Now I have an array that includes the keys of my map. but now I need to compare these keys with some integer. for example :

  开发者_开发知识库            if(weel[1] == 5) 

but as the weel type is Object, I can not do the above and also I cannot cast it to int. how can I do this? is it possible?


Not sure why you want to create a copy of the keys give you can just use the keys.

You can do

List<Integer> keys = new ArrayList<Integer>(sorted_map.keySet());
if (kyes.get(1) == 5)

or

Integer[] keys = (Integer[]) sorted_map.keySet()
                 .toArray(new Integer[sorted_map.size()]);
if (kyes[1] == 5)

or

Iterator<Integer> iter = sorted_map.keySet().iterator();
iter.next(); // skip the first.
if(iter.next() == 5);


Why don't you declare your array as an Integer[] or int[] instead? In the latter case, you can even use == for comparison. However, you also implicitly use unboxing in that case, which might affect performance if you have a huge map.


Your keyset is of type Integer (not int) as you have correctly denoted with Set. So what you are getting out of the array are objects of type Integer, which cannot be cast to an int. What you should do is create an array of type Integer rather than Object, then when you do your comparison you can use the intValue() method of Integer to get it as an int.


Firstly you don't need to use an iterator to populate the array you can call the .toArray() method on the keyset like so:

sortedMap.keySet().toArray();

Then all you have to do is cast each element of the object array to an integer as you use it (Or you could cast the array to an integer array when creating it)

if (((Integer)weel[1]0 == 5){
}

Also you might want to note that your if statment only contains one = sign thats and assignment not a comparison.

EDIT:

On reflection you can also you the toArray Method that actually returns a typed array:

Set<Integer> keySet = new sortedMap.keySet();       
Integer[] weel = {};
weel = keySet.toArray(weel);

you will then have an array of integers which you can compare to any other integer.

0

精彩评论

暂无评论...
验证码 换一张
取 消