java中hashmap按键排序,java初学者:键如何在hashmaps中排序?

i am new to java and was learning the concepts of hashmaps.

I am confused how the keys are sorted in hashmaps.

i understood that its based on string length.

but i am confused how data is sorted when the string length is same.

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

public class HashMapExample

{

public static void main(String args[])

{

Map map = new HashMap(20);//SPECIFYING THE TYPE FOR FINDING HASH CODES.

//Adding values to the HashMap

map.put("key value a", "test value 1");

map.put("key value b", "test value 2");

map.put("key value c", "test value 3");

System.out.println("Retrieving values from HashMap");

retrieveValuesFromListMethod(map);

System.out.println("**********************");

}

/*This method retrieves values from Map

*/

public static void retrieveValuesFromListMethod(Map map)

{

Set keys = map.keySet();

Iterator itr = keys.iterator();

String key;

String value;

while(itr.hasNext())

{

key = (String)itr.next();

value = (String)map.get(key);

System.out.println(key + " - "+ value);

}

}

}

this is my code.

output is

Retrieving values from HashMap

key value c- test value 3

key value b- test value 2

key value a- test value 1

**********************

but instead of a,b,c if i give aa,ab,ac the output is different

Retrieving values from HashMap

key value ab - test value 2

key value aa - test value 1

key value ac - test value 3

**********************

for 1,2,3

Retrieving values from HashMap

key value 1 - test value 1

key value 2 - test value 2

key value 3 - test value 3

**********************

how sorting is done in hashmap? Please help!!

Thanks in advance.

解决方案

java.util.HashMap is unordered; you can't and shouldn't assume

anything beyond that.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant

over time.

java.util.LinkedHashMap uses insertion-order.

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked

list defines the iteration ordering, which is normally the order in

which keys were inserted into the map (insertion-order).

java.util.TreeMap, a SortedMap, uses either natural or custom ordering

of the keys.

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which

constructor is used.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值