1

我从数据库中获取一些记录并添加。HashMap<Integer, Object>然后我将其添加HashMapVector<HashMap<Integer, Object>>. 现在的问题是什么时候。我正在打印Vector,我没有以相同的插入顺序获得记录...请帮助。

public Vector<HashMap<Integer, Object>> executeQueryAsIntegerColumnNames(String aQuery, HashMap<String,String> conditions, String likeQuery){
    LOGGER.info("Query in Execute:"+aQuery);
    LOGGER.info("Query in Execute:"+conditions);
    LOGGER.info("Query in Execute:"+likeQuery);
    Vector <HashMap<Integer,Object>> result = null;

    Connection conn = connection.getMySQLConnection();
    String concond = this.getConditions(conditions);

    try {
        Statement stmt = conn.createStatement();    
        stmt = conn.createStatement();                     
        ResultSet rs = stmt.executeQuery(aQuery + concond);    
        ResultSetMetaData metaInfo = null;
        if(rs != null){
            metaInfo =rs.getMetaData();
        }
        while(rs != null && rs.next()){
            if(result == null){
                result = new Vector<HashMap<Integer, Object>>();
            }
            HashMap<Integer, Object> row = new HashMap<Integer, Object>();

            for(int i = 1 ; i <= metaInfo.getColumnCount(); i++){
                row.put(i, rs.getObject(i));
            }

            result.add(row);
        }
    }catch(Exception ex){
        LOGGER.error("executeQueryAsIntegerColumnNames : "+ex);
    }finally{
        try {
            conn.close();
        } catch (SQLException e) {
            LOGGER.error("Exception :",e);
        }                   
    }            
    LOGGER.info("Befor Returning to Caller : "+result.toString());    
    return result;
}

Vector是否支持插入顺序???如果是,那么这是我的输出 请看一下

返回呼叫者之前:[{1=mah0300537, 2=nabi hussain, 3=Mah03, 4=05:50:00 PM, 5=233346, 6=0}, {1=cha0700003, 2=sita sharan ray, 3 =cha07, 4=05:50:00 PM, 5=233347, 6=2}]

返回呼叫者之前:[{1=cha0700003, 2=sita sharan ray, 3=cha07, 4=05:50:00 PM, 5=233347, 6=2}, {1=mah0300537, 2=nabi hussain, 3 =Mah03, 4=05:50:00 PM, 5=233346, 6=0}]

4

3 回答 3

8

HashMap 不维护插入顺序。请改用LinkedHashMap

于 2013-10-11T13:05:06.707 回答
3

来自 HashMap javadoc:

此类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变。

如果要保持地图中插入元素的顺序,请使用 LinkedHashMap。

于 2013-10-11T13:17:57.483 回答
1

如果您必须维护订单,请使用LinkedHashMaphttp://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

于 2013-10-11T13:13:26.860 回答