gpt4 book ai didi

java - 如何从Java对象中获取元素

转载 作者:行者123 更新时间:2023-12-02 07:22:04 25 4
gpt4 key购买 nike

我有这个 Java 对象,用于生成数据中心 ID 和数据中心名称。

private List<listDatacentersObj> listDatacenters;

public void initListDatacenters() throws SQLException {
// Generate List of Datacenters
listDatacenters = new ArrayList<>();

if (ds == null) {
throw new SQLException("Can't get data source");
}
/* Initialize a connection to Oracle */
Connection conn = ds.getConnection();

if (conn == null) {
throw new SQLException("Can't get database connection");
}
/* With SQL statement get all settings and values */
PreparedStatement ps = conn.prepareStatement("select y.componentstatsid, y.name "
+ "FROM component x, componentstats y where x.componentstatsid = y.componentstatsid and y.componenttypeid = 1000");

try {
//get data from database
ResultSet result = ps.executeQuery();
while (result.next()) {
/* Put the the data from Oracle into Hash Map */
listDatacenters.add(new listDatacentersObj(result.getInt("COMPONENTSTATSID"), result.getString("NAME")));

}
} finally {
ps.close();
conn.close();
}
}

public class listDatacentersObj {

private int datacenterid;
private String datacentername;

public listDatacentersObj(int datacenterid, String datacentername){

this.datacenterid = datacenterid;
this.datacentername = datacentername;

}

public int getDatacenterid() {
return datacenterid;
}

public void setDatacenterid(int datacenterid) {
this.datacenterid = datacenterid;
}

public String getDatacentername() {
return datacentername;
}

public void setDatacentername(String datacentername) {
this.datacentername = datacentername;
}
@Override
public String toString()
{
return datacentername;
}

}

// Get the list with Datacenters
public List<listDatacentersObj> getlistDatacenters() throws SQLException {
// Get the list of Datacenters from Oracle

return listDatacenters;
}

问题是如何使用数据中心 key 获取数据中心名称。与 hashmap 类似,我想根据键获取值。

最佳答案

好吧,如果您的 key 是 componentstatsid,那么只需将检索到的 listDatacentersObj 对象存储在 HashMap 中,如下所示:

// private List<listDatacentersObj> listDatacenters; use the below map instead of this list
private Map<Integer, listDatacentersObj> listDatacenters =
new HashMap<Integer, listDatacentersObj>();

...

public void initListDatacenters() throws SQLException {

...

try {
//get data from database
ResultSet result = ps.executeQuery();
while (result.next()) {
/* Put the the data from Oracle into Hash Map */
final int id = result.getInt("COMPONENTSTATSID");
listDatacenters.put(id, new listDatacentersObj(id, result.getString("NAME")));

}
} finally {
ps.close();
conn.close();
}
}
}

关于java - 如何从Java对象中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14093968/

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