黑马程序员技术交流社区

标题: 集合treset hashset的题目 [打印本页]

作者: yuanqing    时间: 2016-6-24 23:47
标题: 集合treset hashset的题目

1.分析以下需求,并用代码实现:
        (1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
        (2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
        (3)利用四种方式遍历Map集合中的内容,格式:key::value



  1. public class Student {
  2.         private String name;
  3.         private  int age;

  4.        
  5.         public Student(String name, int age) {
  6.                 super();
  7.                 this.name = name;
  8.                 this.age = age;
  9.                
  10.         }
  11.        
  12.         public String getName() {
  13.                 return name;
  14.         }
  15.         public void setName(String name) {
  16.                 this.name = name;
  17.         }
  18.         public int getAge() {
  19.                 return age;
  20.         }
  21.         public void setAge(int age) {
  22.                 this.age = age;
  23.         }

  24.        


  25.        
  26. }
  27. package zuoye;


  28. import java.util.HashMap;
  29. import java.util.Iterator;
  30. import java.util.Map.Entry;
  31. import java.util.Set;

  32. public class Test {

  33.         public static void main(String[] args) {
  34.                 HashMap<Student,String> hs=new HashMap<Student, String>();
  35.                 hs.put(new Student("sam",24),"Beijing");
  36.                 hs.put(new Student("bob",24),"guangzhou");
  37.                 hs.put(new Student("alice",25),"shenzhen");
  38.                 hs.put(new Student("billy",25),"xiamen");
  39.                
  40.         /*        Set<Student> key= hs.keySet();
  41.                 Iterator<Student> it=key.iterator();
  42.                 while(it.hasNext()){
  43.                         Student stu=it.next();
  44.                         System.out.println("姓名是"+stu.getName()+"年龄是"+stu.getAge()+hs.get(stu));
  45.                 }
  46.         }*/
  47.                 /*for(Student a:hs.keySet()){
  48.                         System.out.println("姓名是"+a.getName()+"年龄是"+a.getAge()+"地址是"+hs.get(a));
  49.                 }*/
  50.                
  51.         /*        Set<Entry<Student, String>> key = hs.entrySet();
  52.                 Iterator<Entry<Student, String>> it=key.iterator();
  53.                 while(it.hasNext()){
  54.                         Entry<Student, String> et=it.next();
  55.                         System.out.println("姓名是"+et.getKey().getName()+"年龄是"+et.getKey().getAge()+"地址是"+et.getValue());
  56.                 }*/
  57.                 for(Entry<Student, String> et:hs.entrySet()){
  58.                         System.out.println("姓名是"+et.getKey().getName()+"年龄是"+et.getKey().getAge()+"地址是"+et.getValue());
  59.                 }
  60.         }

  61. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2