Java Map <integer,hashmap <string,=“”string =“”>&gt; </integer,>

时间:2012-05-18 20:15:54

标签: java list collections map hashmap

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

我现在面临的问题是,如果索引大于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之间的索引不存在。因此,最好只迭代现有的地图条目。

6 个答案:

答案 0 :(得分:6)

未对HashMap进行排序或排序。如果您需要插入订单Map,请使用java.util.LinkedHashMap。 如果您需要按密钥排序Map,请使用SortedMap,例如java.util.TreeMap

答案 1 :(得分:4)

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

HashMap不保证密钥的排序。我引用的其他两个Map实现。

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

LinkedHashMap将根据插入的时间对键进行排序。

由于他们正在寻找的行为是因为键是自然排序的,而您恰好自己按顺序插入键,所以这两种情况都可以实现。

答案 2 :(得分:3)

您可以使用LinkedHashMap来保持插入顺序,因为基本地图不保证按键顺序。

答案 3 :(得分:3)

如何使用TreeMap?而不是HashMap。您甚至可以提供自己的订购。

答案 4 :(得分:2)

  

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

因此请将其设为ArrayList而不是LinkedList。这样,list.get(1234)将直接进入该条目 - 它不会迭代它之前的1234个条目。

答案 5 :(得分: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);