在Java中存储一些数据的最佳方法是什么? (数组与ArrayList)

时间:2011-07-01 12:44:04

标签: java arrays arraylist store

目前,我正在从java中的XML文件中提取两个不同的属性(对于我的项目)彼此相关并将它们打印到控制台。但是,我希望能够以引用一个值将检索它的相应对应方式的方式存储它们。例如:

Id: rId11 & Target: image3
Id: rId10 & Target: image2
Id: rId9 & Target: image1

使用这3个值,我想要一种方法来存储每一行​​,但是当我引用“rId”时,我可以得到它相应的“目标”值。我正在考虑使用数组或arrayList,但我不确定哪个更适合我的目的,或者我将如何仅引用一个值并获取另一个值。有人能给我一些建议吗?提前谢谢。

8 个答案:

答案 0 :(得分:4)

如果您的密钥是唯一的,请使用Map

Map<String, String> mak = new HashMap<String, String>();
map.put("rId11","image3");
map.put("rId10","image2");
map.put("rId9","image1");

<强>参考:

否则,创建一个包含键和值的自定义对象,并创建一个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"));

<强>参考:

答案 1 :(得分:2)

使用Map,ID为关键字,Target为值。请注意,Map是一个接口,因此仅定义行为。您需要选择一个特定的实现,例如HashMap。

答案 2 :(得分:2)

你对自己想要的东西有点模棱两可。如果要基于给定键查找值,请将对存储在HashMap(更快)或Hashtable(较慢但线程安全)中。

原始数组(以及更高级List - 基于此类的集合以及ArrayListVector)不能与开箱即用的名称 - 值对一起使用。它们很简单,很好......列表。原始数组可以提供更高的性能,因为您可以避免创建对象,但更高级的List类型集合可以更安全,更灵活。

但是,听起来(?)就像你想要一个Map类型集合而不是List类型一样。

更新:顺便说一下,如果您使用地图,那么您仍然可以使用所有“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
}

答案 3 :(得分:2)

我认为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");

答案 4 :(得分:2)

如果我理解正确,你希望能够找到类似“rId10”的东西,并获得值“image2”(仅限于此)。

如果是这种情况,我认为最好(在速度方面)和最简单的解决方案将是一个哈希表(java.util.Hashtable) - 小心使用Java Generics(在Java 1.5之后)。还可以查看http://en.wikipedia.org/wiki/Hash_table

答案 5 :(得分:1)

如果目标值的“键”是唯一的,并且只有一个目标映射到它们,那么我建议使用java.util.HashMap。您可以通过传入密钥来检索任何目标值。另外,你可以像使用ArrayList一样迭代HashMap。

答案 6 :(得分:1)

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

阅读the Java tutorial about collections

答案 7 :(得分:1)

如果需要动态添加元素

,ArrayList非常有用