2013-10-11 60 views
1

我正在從數據庫獲取一些記錄並在HashMap<Integer, Object>中添加。然後,我將此HashMap添加到Vector<HashMap<Integer, Object>>。現在問題是什麼時候。我正在打印Vector,我沒有以相同的插入順序獲取記錄...請幫助。Java Collections中的奇怪結果

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; 
} 

矢量是否支持插入順序? IF YES則這是我的輸出請看看

Befor返回到主叫方:[{1 = mah0300537,2 =納比侯賽因,3 = Mah03,4 = 05:50:00 PM,5 = 233346,6 = 0},{1 = cha0700003,2 = SITA夏朗射線,3 = cha07,4 = 05:50:00 PM,5 = 233347,6 = 2}]

Befor返回到主叫方:[{1 = cha0700003 ,2 =沙塔沙林射線,3 =沙漠7,4 = 05:50:00 PM,5 = 233347,6 = 2},{1 = mah0300537,2 =沙漠沙漠,3 = Mah03,4 = 05:50:00 PM,5 = 233346,6 = 0}]

+5

HashMap不保留順序。改爲使用LinkedHashMap。 –

+0

可能是,如果你的quey在每次按照不同的順序獲取數據時沒有訂單,那麼當你在hasmap中添加featched值時,訂單可能不同,因此每一次prnt訂單都不同 – Forhad

+1

但是爲什麼Vector >?我認爲簡單的ArrayList對於你的代碼來說已經足夠了。 – vels4j

回答

3

從HashMap中的Javadoc:

此類不保證作爲對地圖的順序;特別是,它不能保證訂單會隨着時間的推移保持不變。

如果要保留插入元素在地圖中的順序,請使用LinkedHashMap。

+1

['Vector' is not deprecated。](http:// docs。 oracle.com/javase/7/docs/api/java/util/Vector.html) – Joni

+0

是的,你是絕對正確的。謝謝修正。 –