我认为HashMap是无序的,当迭代键时,你不知道命令是什么?在此示例中,看起来地图已按键编号排序:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
String[] words = {"Car", "Cat" ,"Hello", "World", "Hi", "Bye", "Dog", "Be"};
Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for (String word: words) {
Integer len = word.length();
List<String> l = map.get(len);
if (l == null) {
l = new ArrayList<String>();
l.add(word);
map.put(len, (ArrayList<String>) l);
}
else {
if (! l.contains(word))
l.add(word);
}
}
System.out.println(map);
}
}
输出:
{2=[Hi, Be], 3=[Car, Cat, Bye, Dog], 5=[Hello, World]}
答案 0 :(得分:5)
是的,但无法保证维持该顺序。
来自Hashmap docs
这个类对地图的顺序做了无保证;特别是,它不保证订单会随时间保持不变。
你的替补标记不足以决定它。
查看TreeMap如果您需要排序顺序
地图是根据其键的自然顺序排序的,或者是在地图创建时提供的比较器,具体取决于使用的构造函数
答案 1 :(得分:2)
对于小型hashCodes,HashMap变成一个数组(因为这是在下面使用的)没有要求它这样做,但它恰好是最简单的实现。
简而言之,如果向HashSet或HashMap添加0到10,您将按顺序获取它们,因为容量足以按顺序布局这些值。
答案 2 :(得分:1)
Treemap是一个有序的地图,其中包含按排序顺序排列的键,而HashMap无法保证您排序的地图。因此,如果您想要排序的键,请始终选择Treemap