gpt4 book ai didi

java - 在 Java 中检索和迭代 map 类数据库

转载 作者:行者123 更新时间:2023-12-01 09:35:23 26 4
gpt4 key购买 nike

我有以下类文件

数据库类

public class DBClass {

private static Map<Long, Fish> fishs= new HashMap<>();

public static Map<Long, Fish> getFishs(){
return fishs;
}
}

鱼类类别

public class Fish{

private long id;
private String fishName;
private String descr; //description
private double weight;
private String fishLoc; //location

public Fish(){

}

public Fish(long id,String fishName,String descr,double weight,String fishLoc){
this.id = id;
this.fishName= fishName;
this.descr = descr;
this.weight= weight;
this.fishLoc = fishLoc;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public String getFishName() {
return fishName;
}

public void setFishName(String fishName) {
this.fishName= fishName;
}

public String getDescr() {
return descr;
}

public void setDescr(String descr) {
this.descr = descr;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight ;
}

public String getFishLoc() {
return fishLoc;
}

public void setFishLoc(String fishLoc) {
this.fishLoc = fishLoc;
}

}

FishServ 类

public class FishServ {

private Map<Long, Fish> fishDB = DatabaseClass.getFishs();

public FishServ (){

fishDB.put(1L,new Fish(1,"Starfish","Shape like a star",5.25,"Atlantic Ocean"));
fishDB.put(2L,new Fish(2,"Salmon","Looks like dinner",3.25,"Pacific Ocean"));
fishDB.put(3L,new Fish(3,"Sardines","Plenty to go around",0.05,"Rainfall"));
}

public List<Fish> getAllFishs(){
return new ArrayList<Fish>(fishDB.values());
}
}

DatabaseTest 类(不工作)

public class DBTest{
private static Map<Long, Fish> fishDB = DatabaseClass.getFishs();

public static void main(String[] args){
Iterator entries = fishDB.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
}

System.out.println("FAILED BIG TIME");
}
}

没有输出,也没有错误,我不知道如何迭代这个数据库映射,我尝试了 DatabaseTest 但没有成功。

我想要做的是迭代数据库 ID 并检索值对象,然后将值对象分成例如FishName、描述等,并将每个变量分配给 DatabaseTest 类。

最佳答案

在您的测试中,您永远不会用任何内容填充数据库映射。因此,如果它为空,您的循环将不会运行。

如果您实际使用 FishServ 类,那么您只需获取在 getAllFishs() 中返回的列表,然后像这样迭代:

FishServ fishServ = new FishServ();
List<Fish> fishList = fishServ.getAllFishs();
for (Fish fish in fishList) {
// Process fish and get contents, description, etc.
}

关于java - 在 Java 中检索和迭代 map 类数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005136/

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