1

我需要将结果集转换为地图地图。我不使用地图列表的原因是因为我不想遍历整个列表来获取特定行。

我现在面临的问题是,如果索引大于 16,则不再对 HashMap 的条目进行排序。

现在我尝试了以下简单测试:

    public static void main(String[] args) {

    Map<Integer, String> map = new HashMap<Integer, String>();

    //creating 20 rows from 1 to 20
    for (int i = 1; i <= 20; i++){
        map.put(i, "ROW "+i);   
    }


    //returning all the rows the map contains. Look at position 16.
    for(int key : map.keySet()){
        System.out.println(key);    
    }
}

输出如下(查看位置 16 到 20。它们完全无序):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 16 19 18 20

如果有人能解释为什么会发生这种情况,我将不胜感激。

顺便说一下:

我不能使用这样的东西:

for (int i = 0; i < map.size; i++){
    map.get(i) //...and so on

}

因为我不知道索引是否存在。可能是从200到800的索引不存在。所以最好只遍历地图的现有条目。

4

6 回答 6

6

AHashMap未排序或排序。如果您需要插入有序Map使用java.util.LinkedHashMap. 如果您需要Map按键排序,请使用SortedMap诸如java.util.TreeMap

于 2012-05-18T20:17:16.867 回答
4

您应该使用TreeMapLinkedHashMap而不是 HashMap,具体取决于您是否希望元素分别按其自然顺序或插入顺序排序。

HashMap 不保证键的顺序。我引用的其他两个 Map 实现确实如此。

TreeMap 将根据键的自然顺序对键进行排序,这意味着键必须实现 Comparable 或者您必须提供自己的比较器才能确定顺序。

LinkedHashMap 将根据插入的时间保持键的顺序。

由于您正在寻找的行为是键自然排序,并且您碰巧自己按顺序插入键,因此任何一种实现都适用于这种情况。

于 2012-05-18T20:18:48.300 回答
3

您可以使用LinkedHashMap来保持插入顺序,因为基本映射不保证键的顺序。

于 2012-05-18T20:17:27.477 回答
3

使用 TreeMap 怎么样?而不是HashMap。您甚至可以提供自己的订单。

于 2012-05-18T20:18:58.813 回答
2

我不使用地图列表的原因是因为我不想遍历整个列表来获取特定行。

所以让它成为一个ArrayList而不是一个LinkedList。这样,list.get(1234)将直接进入该条目——它不会遍历之前的 1234 个条目。

于 2012-05-18T21:53:14.977 回答
1

我认为您面临的问题是因为 HashMap 的默认大小。

根据标准java文档,

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
 * The load factor used when none specified in constructor.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
    table = new Entry[DEFAULT_INITIAL_CAPACITY];
    init();
}

因此,在第 16 个元素之后您没有得到正确的输出。

根据 JavaDoc,

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

尝试以下(具有初始容量的参数化构造函数),

Map<Integer, String> map = new HashMap<Integer, String>(32);
于 2012-05-28T14:06:03.060 回答