解析为Java ArrayList对

时间:2015-01-08 18:59:28

标签: java arrays parsing arraylist multidimensional-array

我有一个Java问题,我试图解决,直到现在我无法得到它。使用下面的代码,我在控制台中得到了一个XML Parser的响应;这一切都在这一行:

[359710042040320, Suzuki SX4 "BB71521", 359710042067463, Chevrolet Tahoe Noir "Demonstration", 359710042091273, Isuzu D'Max AA-08612, 359710042110768, Toyota 4 Runner]

但是我的目标是得到一个像ArrayList一样的响应,其中每个Device ID和每个Description都在一起,用逗号分隔。

(DeviceID)            (Descripcion)
359710042040320, Suzuki
359710042067463, Chevrolet

2 个答案:

答案 0 :(得分:1)

而不是使用List<String>尝试使用HashMap<String, String>。要定义它,你会这样做:

HashMap<String, String> result = new HashMap<String,String>();

然后在你的循环中用以下代替result.add(value)

result.put(name,value);

现在,您可以通过名称(密钥)从地图访问您的值:

result.get(name);//Note Name is a string that holds you key value

如果您需要查看更多文档:HashMap Documentation

答案 1 :(得分:1)

正如Dott Bottstein所说,HashMap可能就是你想要的。我将使用LinkedHashMap,因为LinkedHashMaps保留原始订单,而HashMaps根本不保证订单。

您可以采取以下措施:

Map<String, String> resultMap = new LinkedHashMap<String, String>();
for (int i = 0; i < nodeList.getLength(); i++) {
    String deviceID = nodeList.item(i).getFirstChild().getNodeValue();
    String descripcion = nodeList.item(i).getAttributes().getNamedItem("name").toString();
    resultMap.put(deviceID, descripcion);
}

//ok, lets print out what's in the Map
Iterator<String> iterator = resultMap.keySet().iterator(); 
while(iterator.hasNext()){
    String deviceID = iterator.next();
    String descripcion = resultMap.get(key);
    System.out.println(deviceID  + ", " + descripcion);
}

Maps have the big advantage that afterwards you can look up a descripcion very quickly if you have the deviceID.

如果你真的想要一个ArrayList,你可以用两种方式来做:

1)String []数组的ArrayList,长度为2

static int DEVICE_ID = 0;
static int DESCRIPCION = 1;

List<String[]> result = new ArrayList<String[]>();
for (int i = 0; i < nodeList.getLength(); i++) {
    String[] vehicleArray = new String[2];
    vehicleArray[DEVICE_ID] = nodeList.item(i).getFirstChild().getNodeValue();
    vehicleArray[DESCRIPCION] = nodeList.item(i).getAttributes().getNamedItem("name").toString();

    result.add(vehicleArray);
}

或2)您可以创建一个类来保存车辆数据:

class Vehicle{

    String deviceID;
    String descripcion;

    public Vehicle(String deviceID, String descripcion){
        this.deviceID = deviceID;
        this.descripcion = descripcion;
    }

}

然后创建一个车辆实例列表:

List<Vehicle> result = new ArrayList<Vehicle>();
for (int i = 0; i < nodeList.getLength(); i++) {

   String deviceID = nodeList.item(i).getFirstChild().getNodeValue();
   String descripcion = nodeList.item(i).getAttributes().getNamedItem("name").toString();

    result.add(new Vehicle(deviceID, descripcion));
}

最后,您可能希望将ID保留为长号而不是字符串。这不是HashMapList<Vehicle>想法的问题,但它不适用于List<String[]>这个想法。 HashMaps可以很好地使用一个很长的密钥。密钥必须是长对象,但Java会自动从long转换为Long对象,因此您甚至不必考虑它,只需将长基元设置为密钥即可。