使用Java检索和迭代映射类数据库

时间:2016-08-17 19:50:29

标签: java hashmap

我有以下类文件

数据库类

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 Class

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,description等,并为DatabaseTest类分配每个变量。

1 个答案:

答案 0 :(得分:1)

在测试中,您永远不会用任何东西填充数据库映射。所以,如果它是空的,你的循环就不会运行。

如果您实际使用的是FishServ类,那么您可以在getAllFishs()中获取要返回的列表,并按如下方式迭代:

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