2015-10-28 97 views
1

我試圖通過HashMap循環,然後爲每個鍵我想訪問與鍵關聯的對象(Shipment)並訪問我的數組列表進一步分析目的。 HashMap中的每個對象/鍵具有相同的數組列表(metricList)。我似乎無法訪問它,雖然我已經檢查了私人/公共事物。有人能指引我朝着正確的方向嗎?Java - 通過HashMap訪問對象的數組列表(Key is object)

我想我需要也許得到我的對象的類,然後使用方法「getList」...我試過沒有運氣。

這是代碼(刪除無關的部分),如果有幫助的樣本:

這是我的目標:

public class Shipment{ 

    //Members of shipment 
    private final String shipment; 
    public Date creationDate; 
    public int creationTiming; 
    public int processingTiming; 
    public ArrayList<Integer> metricList; 

    public void createArrayList() { 
     // create list 
     metricList = new ArrayList<Integer>(); 
     // add metric to list 
     metricList.add(creationTiming); 
     metricList.add(processingTiming); 
    } 

    public ArrayList<Integer> getList() { 
     return metricList; 
    } 
} 

這是我創建一個HashMap,並通過不同的分析運行的類:

public class AnalysisMain { 

    public static Map<String, Shipment> shipMap = new HashMap(); 

    public static void main(String[] args) {  
     try { 
     ... // Different calls to analysis 
     } 
     catch {} 
    } 
} 

這是出現問題(它不承認,我已經有一個「metricList」,問我是否要創建局部變量)

public class Metric_Analysis{ 
    public static void analyze() throws Exception{ 

     ResultSet rs; 

      try { 
       rs = getSQL("SELECT * FROM TEST_METRICS"); 
      } 
      catch(Exception e) { 
       //Pass the error 
       throw new java.lang.Exception("DB Error: " + e.getMessage()); 
      } 

      Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator(); 
      while(iterator.hasNext()){ 

        Iterator<String> metricIterator = metricList.iterator(); 

        //Above is the Array List I want to access and loop through 
        //I will then perform certain checked against other values on a table... 

        while (metricIterator.hasNext()) { 
        //I will perform certain things here 
        } 
      } 
    } 
} 
+0

'metricList'不'Metric_Analysis'知道,你應該先得到它。 – Maroun

+0

@MarounMaroun我試圖把「getList();」在「while(iterator.hasNext())」之後,但它仍然不起作用,詢問我是否在我的Shipment類創建方法時創建方法...:s – Aurax22

回答

1

您需要將列表從您的貨件中取出。 您可以使用iterator.next();從迭代器訪問該對象。 這也會將指針設置爲List/Map中的下一個條目。

更改代碼:

Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator(); 
      while(iterator.hasNext()){ 

        // Get the Entry from your Map and get the value from the Entry 
        Entry<String, Shipment> entry = iterator.next(); 
        List<Integer> metricList = entry.getValue().getList(); 

        Iterator<String> metricIterator = metricList.iterator(); 

        //Above is the Array List I want to access and loop through 
        //I will then perform certain checked against other values on a table... 

        while (metricIterator.hasNext()) { 
        //I will perform certain things here 
        } 
      } 
+0

就是這樣......現在所有的工作,謝謝red13! – Aurax22