黑马程序员技术交流社区
标题:
集合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
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package zuoye;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Student,String> hs=new HashMap<Student, String>();
hs.put(new Student("sam",24),"Beijing");
hs.put(new Student("bob",24),"guangzhou");
hs.put(new Student("alice",25),"shenzhen");
hs.put(new Student("billy",25),"xiamen");
/* Set<Student> key= hs.keySet();
Iterator<Student> it=key.iterator();
while(it.hasNext()){
Student stu=it.next();
System.out.println("姓名是"+stu.getName()+"年龄是"+stu.getAge()+hs.get(stu));
}
}*/
/*for(Student a:hs.keySet()){
System.out.println("姓名是"+a.getName()+"年龄是"+a.getAge()+"地址是"+hs.get(a));
}*/
/* Set<Entry<Student, String>> key = hs.entrySet();
Iterator<Entry<Student, String>> it=key.iterator();
while(it.hasNext()){
Entry<Student, String> et=it.next();
System.out.println("姓名是"+et.getKey().getName()+"年龄是"+et.getKey().getAge()+"地址是"+et.getValue());
}*/
for(Entry<Student, String> et:hs.entrySet()){
System.out.println("姓名是"+et.getKey().getName()+"年龄是"+et.getKey().getAge()+"地址是"+et.getValue());
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2