gpt4 book ai didi

Java - 通过HashMap访问对象的数组列表(Key是对象)

转载 作者:行者123 更新时间:2023-11-30 07:50:20 25 4
gpt4 key购买 nike

我试图循环遍历 HashMap,然后对于每个键,我想访问与该键关联的对象(发货)并访问我的数组列表以进行进一步分析。 HashMap中的每个对象/键都有相同的数组列表(metricList)。尽管我已经检查了私有(private)/公共(public)事物,但我似乎无法访问它。有人能指出我正确的方向吗?

我想我可能需要获取对象的类,然后使用方法“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
}
}
}
}

最佳答案

您需要从货件中取出 list 。您可以通过迭代器访问该对象: iterator.next();这还将把指针设置为列表/ 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
}
}

关于Java - 通过HashMap访问对象的数组列表(Key是对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com