我正在尝试遍历HashMap,然后为每个键我想要访问与该键关联的对象(Shipment)并访问我的数组列表以进行进一步的分析。 HashMap中的每个对象/键都具有相同的数组列表(metricList)。我似乎无法访问它,虽然我检查了私人/公共事物。有人能指出我正确的方向吗?
我想我可能需要得到我的对象的类,然后使用方法" 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 {}
}
}
这就是问题发生的地方(它不知道我已经有了#34; metricList&#34;,询问我是否要创建局部变量)
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 :(得分: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
}
}