TreeMap不能包含重复的键。TreeMap不能包含null键。但是,它可以具有空值。
首先让我们看看如何创建TreeMap-
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
以键值对的形式添加一些元素-
m.put(1,"India"); m.put(2,"US"); m.put(3,"Australia"); m.put(4,"Netherlands"); m.put(5,"Canada");
以下是创建TreeMap并添加键值对的示例-
import java.util.*; public class Demo { public static void main(String args[]) { TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"India"); m.put(2,"US"); m.put(3,"Australia"); m.put(4,"Netherlands"); m.put(5,"Canada"); for(Map.Entry e:m.entrySet()) { System.out.println(e.getKey()+" "+e.getValue()); } } }
输出结果
1 India 2 US 3 Australia 4 Netherlands 5 Canada