{"ABC的员工1", "ABCX"}, {"ABC的员工2", "ABCY"}, {"ABC的员工3", "ABCZ"}
这些数据是通过
RefCursor
从数据库中获取的。我有一个需求,需要保留从数据库中读取数据的顺序。由于我的数据类似于“键-值”对,我考虑使用一个有序的
Map
实现。因此选择了LinkedHashMap
。//defined as a static map inside a common utlity class
public class Common{
public static final LinkedHashMap<String, String> empMap = new LinkedHashMap<String, String>();
}
//rs is the resultset
if (rs != null) {
while (rs.next()) {
key = rs.getString("name_text");
value = rs.getString("id");
Common.empMap.put(key, value);
}
}
我需要将从数据库中检索到的密钥按照相同的顺序传递给客户端(游标)。
List<String> empList = new ArrayList<String>(Common.empMap.keySet());
keySet() - 文档中表示“返回此映射中包含的键的Set视图。该集合由映射支持,因此对映射的更改会反映在集合中,反之亦然”。
我的期望是,由于ArrayList
也是一个有序集合,我应该以相同的方式获取/插入到Map
中的键。
当我做了一个示例测试程序时,结果与预期相符。
public class LinkedMap {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("Employee 1 of ABC", "ABCX");
map.put("Employee 2 of ABC", "ABCY");
map.put("Employee 3 of ABC", "ABCZ");
ArrayList<String> list = new ArrayList<String>(map.keySet());
System.out.println(list);
}
}
输出结果:[ABC公司的员工1,ABC公司的员工2,ABC公司的员工3]
然而我的问题是,这个输出结果是保证的还是随机的,并且可能会有所不同(?)
- 更新于2019年9月14日
为了避免混淆,我将答案与问题分开。
LinkedHashMap
,而不是模糊的Map
:) - ZhongYu