2015-10-28 63 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