[英]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保留為長號而不是字符串。 對於HashMap
或List<Vehicle>
想法來說,這不是問題,但是對於List<String[]>
想法來說,這是行不通的。 HashMaps使用Long鍵可以很好地工作。 密鑰必須是Long對象,但是Java會自動將long從long轉換為Long對象,因此您甚至不必考慮它,只需將long原語設置為密鑰就可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.