[英]Convert generic list to java object
I am performing a query on a database and I get in return a generic List of objects. 我正在对数据库执行查询,然后得到一个通用的对象列表。 The overall object is structured as followed: 总体对象的结构如下:
List<E> objDetails =
[0] --> ["name1", "value1"]
[1] --> ["name2", "value2"]
....
[n] --> ["nameN", "valueN"]
In short, I get back an array of objects, and in each element, there are name and values pairs that I want access to. 简而言之,我得到了一个对象数组,在每个元素中,都有要访问的名称和值对。 What is the easiest way to get to these values? 获得这些价值的最简单方法是什么? I am thinking of casting this whole list into a perhaps self-designed class that can hold names/values. 我正在考虑将整个列表转换为一个可以自行设计的可以容纳名称/值的类。 The catch is that one is a string and the other is an integer. 问题是一个是字符串,另一个是整数。
What are my options? 我有什么选择?
EDIT: 编辑:
Here are two classes I tried defining in order to solve this problem 这是我尝试定义的两个类以解决此问题
private static class Clinic {
public List<ClinicDetails> details;
}
private static class ClinicDetails {
private Integer objectID;
private String healthName;
}
List<Clinic> clinic = DataServices.getResult(q);
EDIT 2: 编辑2:
Here is how I solved this problem 这是我解决这个问题的方法
List<Object[]> clinic = DataServices.getResult(q);
for(Object[] obj: clinic) {
for(int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
// will store in my own list now that I can access it
}
}
A simple map would look like this: 一个简单的地图如下所示:
Map m=new HashMap<String, String>();
m.put("Key", "Value");
m.put("Key2", "Value2");
assertEquals(m.get("Key"), "Value");
assertEquals(m.get("Key2"), "Value2");
These solve a lot of use cases but aren't very good for long-term reusable objects. 这些解决了很多用例,但对于长期可重用的对象来说并不是很好。 Everyone uses "Hashes" but if you are good you'll isolate their usage to a single method or a single class. 每个人都使用“哈希”,但是如果您很好,则可以将其用法隔离到单个方法或单个类中。
This would implement a generic object that would be reuseable as you've described. 这将实现一个通用对象,该对象可以如您所描述的那样被重用。
Cheers! 干杯!
` public interface node<K,N> {
public K getKey();
public N getValue();
}
public class LogicalNode<K,N> implements node<K,N>{
private K key;
private N value;
public LogicalNode(K key, N value) {
this.key = key;
this.value = value;
}
public K getKey() {return key;}
public N getValue() {return value;}
}
public class arr2lst {
public static void main(String[] args) {
ArrayList<node<String, Integer>> rs = new ArrayList<node<String,Integer>>();
rs.add(new LogicalNode<String, Integer>("name", nbr));
rs.add(new LogicalNode<String, Integer>("name2", nbr2));
}
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.