gpt4 book ai didi

Java引用另一个类

转载 作者:行者123 更新时间:2023-12-01 10:03:16 24 4
gpt4 key购买 nike

我有以下两个类“动物”和“动物园”,如下所示,

动物类

public class Animal {
private int id;
private String name;
private String animal_order;
private String family;
private String genus;
private String species;
private int number_avilable;
private Zoo _zoo;

public Animal() {

}

public Animal(ArrayList<Animal> allAnimals) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

public Animal (int id, String name, String animal_order, String family, String genus, String species,int number_avilable, Zoo _zoo){
this.id = id;
this.name = name;
this.animal_order = animal_order;
this.family = family;
this.genus = genus;
this.species = species;
//this.zoo = zoo;
this.number_avilable = number_avilable;
this._zoo = _zoo;

}
}

动物园课

public class Zoo {
private String zoo_name;
private String link;
private String lat;
private String lng;
private String postcode;
private String image;

public Zoo() {

}

public Zoo(ArrayList<Zoo> allZoos) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

public Zoo (String zoo_name, String link,String postcode, String image){
this.zoo_name = zoo_name;
this.link = link;
//this.lat = lat;
//this.lng = lng;
this.postcode = postcode;
this.image = image;
}
}

正如您从我的代码中看到的,我尝试在 Animal 中引用动物园类。我在 Animal 类中有以下方法,

public static ArrayList<Animal> getAllAnimals() throws Exception {
PreparedStatement query = null;
Connection conn = null;

ArrayList<Animal> results = new ArrayList();
try {

// connect to database
conn = Database.mySqlDBConn().getConnection();
// run a query
query = conn.prepareStatement("{CALL get_animal()}");
ResultSet rs = query.executeQuery();
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String animal_order = rs.getString("animal_order");
String family = rs.getString("family");
String genus = rs.getString("genus");
String species = rs.getString("species");
int number_avilable= rs.getInt("number_avilable");
String zoo_name = rs.getString("zoo_name");
String link = rs.getString("link");
String postcode = rs.getString("postcode");
String image = rs.getString("image");
Zoo _zoo = new Zoo(zoo_name, link, postcode, image);
Animal animal = new Animal(id, name,animal_order,family, genus, species,number_avilable, _zoo);
results.add(animal);
}
}
}

上面的方法应该返回一个包含动物和动物园的数组列表,但目前它只返回动物而不是动物园信息。我一直在通过堆栈溢出来获取类引用和其他内容,但无法找出线索。

仅供引用,我的存储过程运行良好。

最佳答案

你想要一个同时包含动物和动物园的ArrayList吗?看起来你只是将动物添加到数组列表中,并将动物园添加到动物中,所以如果你想获取动物园,只需在 Animal 类中添加一个 getter 即可:

public Zoo getZoo() {
return _zoo;
}

关于Java引用另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649951/

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