的順序在Java中的HashMap和希望的HashSet下創建一個基於條目新LinkedHashMap的目前如何創建基於我有一個LinkedHashMap的HashSet的
import java.util.*;
public class LinkedHashMapDemo {
public static void main(String args[]) {
// Currently empty
LinkedHashMap<String, String> newhashmap = new LinkedHashMap<String, String>();
// old hash map
LinkedHashMap<String, String> oldhashmap = new LinkedHashMap<String, String>();
// Put elements to the map
oldhashmap.put("Zara", "zaravalue");
oldhashmap.put("Mahnaz", "Mahnazvalue");
oldhashmap.put("Ayan", "Ayanvalue");
oldhashmap.put("Daisy", "Daisyvalue");
oldhashmap.put("Qadir", "Qadirvalue");
HashSet<String> hs = new HashSet<String>();
// add elements to the hash set
hs.add("Zara");
hs.add("Ayan");
hs.add("Qadir");
Iterator iterator = hs.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = oldhashmap.get(key);
}
}
}
,使新newhashmap外觀作爲
newhashmap.put("Zara", "Zaravalue");
newhashmap.put("Ayan", "Ayanvalue");
newhashmap.put("Qadir", "Qadirvalue");
newhashmap.put("Mahnaz", "Mahnazvalue");
newhashmap.put("Daisy", "Daisyvalue");
請讓我知道這可能
您不能依賴HashSet或HashMap中元素的順序。 – Eran
當你的HashSet只包含'Zara,Ayan,Qadir'基於哪個規則的條目'Mahnaz,Daisy'被添加到'newhashmap'? – SubOptimal
@Eran這就是爲什麼他使用LinkedHashMap –