欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Map集合

程序员文章站 2022-07-13 09:21:05
...

Map<String, Student> m = new Hashtable<String,Student>();

Map集合

每一个key的值都不一样,否则指向的是同一个value。但是value可以一样。

Map集合

来看一个简单的代码:

 @Test
   public void test() {
	   Map<String, Student> m = new Hashtable<String,Student>();
	   m.put("qqqqq",new Student("ww",34));  //存入索引和值
	  Student s = m.get(new String("qqqqq"));
	  Student ss = m.get("qqqqq");
	  System.out.println(s.getName());
	  System.out.println(ss.getAge());
   }

输出结果为:Map集合

再来看一个输出key的值,value的值,key和value一块输出的值。

@Test
   public void test1() {
	   Map<String, Student> m = new Hashtable<String,Student>();
	   m.put("A",new Student("ww",32));
	   m.put("B",new Student("ww",35));
	   m.put("C",new Student("ww",323));
	   
	   m.put("D",new Student("ww",34));
	   m.put("E",new Student("ww",39));
	   //得到key
	   Set<String> s = m.keySet();
	   for(Iterator<String> iter = s.iterator();iter.hasNext();) {
		   System.out.println(iter.next());
	   }
	   //得到value
	   Collection<Student> s1 = m.values();
	   for(Iterator<Student> iter = s1.iterator();iter.hasNext();) {
		   System.out.println(iter.next());
	   }
	   //key和value一块输出(entry)
	 Collection<Entry<String, Student>> s2 = m.entrySet();
	   for(Iterator<Entry<String, Student>> iter = s2.iterator();iter.hasNext();) {
		   Entry<String, Student> e = iter.next();
		   System.out.println(e.getKey()+":"+e.getValue());
	   }
   }