0
点赞
收藏
分享

微信扫一扫

hashmap,使用iterator读取后顺序改变

杰克逊爱学习 2022-12-07 阅读 139

public LinkedHashMap<String, String> ReadDistrictAndCity() {


LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();


SAXReader reader = new SAXReader();


Document doc = null;


try {


InputStream in = getClass().getClassLoader().getResourceAsStream(


"district-city.xml");


doc = reader.read(in);


} catch (DocumentException e1) {


e1.printStackTrace();


}


Element RECORDS = doc.getRootElement();


Element foo = null;


for (Iterator i = RECORDS.elementIterator("RECORD"); i.hasNext();) {


foo = (Element) i.next();


// System.out.println(foo.elementText("CITY").toString()+"___"+foo.elementText("DISTRICT").toString());


map.put(foo.elementText("CITY").toString(), foo.elementText(


"DISTRICT").toString());


}


return map;


}



采用LinkedHashMap读取后顺序不会乱


hashmap类是散列映射并不保证它的元素顺序.因此,元素加入散列映射的顺序并不一定是它们被迭代函数读出的顺序,如果想要保持顺序的话可以使用LinkedHashMap,可以保证迭代输出的顺序和输入的一样


举报

相关推荐

0 条评论