[英]What is the Best Way to Store some data in Java? (Array vs ArrayList)
所以目前,我正在从 java 中的 XML 文件中提取两个不同的属性,这些属性(对于我的项目)彼此相关,然后将它们打印到控制台。 但是,我希望能够以引用一个值将检索它对应的对应项的方式存储这些。 例如:
Id: rId11 & Target: image3
Id: rId10 & Target: image2
Id: rId9 & Target: image1
使用这 3 个值,我想要一种存储每一行的方法,但是当我引用“rId”时,我可以获得它对应的“目标”值。 我正在考虑使用数组或 arrayList,但我不确定哪个更适合我的目的,或者我不确定 go 关于仅引用一个值并获取另一个值的确切程度。 谁能给我一些建议? 先感谢您。
如果您的密钥是唯一的,请使用Map
。
Map<String, String> mak = new HashMap<String, String>();
map.put("rId11","image3");
map.put("rId10","image2");
map.put("rId9","image1");
参考:
否则,创建一个包含键和值的自定义 Object 并创建一个List
(或Set
???)。
public class Entry {
private final String id;
private final String value;
public Entry(String id, String value) {
this.id = id; this.value = value;
}
public String getId() { return id; }
public String getValue() { return value; }
// also implement equals() and hashCode(), please
}
List<Entry> entries = new ArrayList<Entry>();
entries.add(new Entry("rId11","image3"));
参考:
使用Map ,以 Id ad 作为键,以 Target 作为值。 请注意,Map 是一个接口,因此仅定义行为。 您将需要选择一个特定的实现,例如 HashMap。
你对你想要什么有点模棱两可。 如果要根据给定键查找值,则将这些对存储在HashMap (更快)或Hashtable (更慢但线程安全)中。
原始 arrays (以及更高级的基于List的 collections 和ArrayList或Vector )不适用于开箱即用的名称-值对。 它们只是,嗯......列表。 原始 arrays 可以提供更高的性能,因为您避免创建对象,但更高级的列表类型 collections 可以更安全、更灵活。
尽管如此,听起来(?)就像你想要一个Map类型集合而不是List类型一。
更新:顺便说一句,如果您使用 Map 那么您仍然可以使用所有“rId”值的列表。 它实际上是一个Set数据类型,但这只是 List 的一个特殊表亲,不允许重复:
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("rId11","image3");
// ... additional put's for the other values
Set<String> myRids = myMap.keySet();
for(String rId : myRids) {
// do whatever you want with each rId one-by-one, etc
// You could also use "myRids.iterator()" to work with an Iterator instead
}
我认为 java.util.HashMap 会更适合此要求,尤其是在不需要排序的情况下。
// not sure what types these are but this would work better
Map<String, String> m = new HashMap<String, String>();
m.put("rId11", "image3");
String other = m.get("rId11");
如果我理解正确,您希望能够寻找“rId10”之类的东西并获得值“image2”(仅此而已)。
If that is the case,I think the best (in terms of speed) and easiest solution will be a hash table (java.util.Hashtable) - be careful to use Java Generics as well (after Java 1.5). 查看http://en.wikipedia.org/wiki/Hash_table也。
如果目标值的“键”是唯一的并且只有一个目标映射到它们,那么我建议使用 java.util.HashMap 代替。 您可以通过传入键来检索任何目标值。 另外,您可以像 ArrayList 一样迭代 HashMap。
public class Item {
private String id;
private String target;
public Item(String id, String target) {
this.id = id;
this.target = target;
}
public String getId() {
return this.id;
}
public String getTarget() {
return this.target;
}
}
List<Item> items = new ArrayList<Item>();
// or
Map<String, Item> itemsIndexedById = new HashMap<String, Item>();
// depending on your use-case
如果您需要动态添加元素,ArrayList 很有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.