繁体   English   中英

解析为Java ArrayList对

[英]Parsing into a Java ArrayList pair

我在Java中有一个要解决的问题,直到现在我还是无法解决。 在下面的代码中,我从控制台中的XML分析器得到了响应。 都是这样的:

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

但是我的目标是获得像成对的ArrayList这样的响应,其中每个设备ID和每个Description在一起,并以逗号分隔。

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

代替使用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文档

正如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)长度为2的String []数组的ArrayList

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;
    }

}

然后创建一个Vehicle实例列表:

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使用Long键可以很好地工作。 密钥必须是Long对象,但是Java会自动将long从long转换为Long对象,因此您甚至不必考虑它,只需将long原语设置为密钥就可以使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM