要跟踪插入顺序,如果是Map,则可以使用Map.Entry()。假设我们有以下LinkedHashMap-
Map<String, Integer>map = new LinkedHashMap<>(); map.put("Jack", 0); map.put("Tim", 1); map.put("David", 2); map.put("Tom", 3); map.put("Kevin", 4); map.put("Jeff", 5);
现在,遍历Map.Entry并使用Key和Value正确获取插入顺序-
for (Map.Entry<String, Integer>entry: map.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); }
import java.util.LinkedHashMap; import java.util.Map; public class Demo { public static void main(String[] args) { Map<String, Integer>map = new LinkedHashMap<>(); map.put("Jack", 0); map.put("Tim", 1); map.put("David", 2); map.put("Tom", 3); map.put("Kevin", 4); map.put("Jeff", 5); map.put("Katies", 6); map.put("Steve", 7); map.put("Andrew", 8); map.put("Angelina", 9); for (Map.Entry<String, Integer>entry: map.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } }
输出结果
Jack => 0 Tim => 1 David => 2 Tom => 3 Kevin => 4 Jeff => 5 Katies => 6 Steve => 7 Andrew => 8 Angelina => 9