900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Java——(1)定义一个学生类Student 包含属性:姓名(String name) 年龄(int age)

Java——(1)定义一个学生类Student 包含属性:姓名(String name) 年龄(int age)

时间:2019-03-28 01:47:15

相关推荐

Java——(1)定义一个学生类Student 包含属性:姓名(String name) 年龄(int age)

分析以下需求,并用代码实现:

(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)

(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value

(3)利用四种方式遍历Map集合中的内容,格式:key::value

代码实现:

(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)

public class Student {String name;int age;public Student(String name, int age) {super();this.name = name;this.age = age;}public Student() {super();}@Overridepublic String toString() {return "Student [姓名:" + name + ", 年龄:" + age + "]";}}

(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value

(3)利用四种方式遍历Map集合中的内容,格式:key::value

import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;/** 分析以下需求,并用代码实现:(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value(3)利用四种方式遍历Map集合中的内容,格式:key::value*/public class StudentMap {public static void main(String[] args) {HashMap<Student, String> hp = new HashMap<Student,String>();hp.put(new Student("张三",20), "上海");hp.put(new Student("李四",18), "天津");hp.put(new Student("王五",22), "河北");hp.put(new Student("赵六",19), "湖南");hp.put(new Student("老八",18), "安徽");SetMethod1(hp);SetMethod2(hp);}public static void SetMethod1(HashMap<Student, String> hp) {//调用hp集合方法entrySet方法,将hp集合的键值对关系对象,存储到Set集合Set<Map.Entry<Student, String>> studentSet = hp.entrySet();System.out.println("调用hp集合方法entrySet方法,用Iterator迭代取出key:");Iterator<Map.Entry<Student, String>> studentIt = studentSet.iterator();while(studentIt.hasNext()) {Map.Entry<Student, String> entry = studentIt.next();Student studentKey = entry.getKey();String value = entry.getValue();System.out.println("\t"+studentKey+"的地址:"+value);}System.out.println("\n调用hp集合方法:entrySet方法,用for···each循环取出key:");for(Map.Entry<Student, String> me : hp.entrySet()) {Student studentKey = me.getKey();String value = me.getValue();System.out.println("\t"+studentKey+"的地址:"+value);}}public static void SetMethod2(HashMap<Student, String> hp) {//调用hp集合方法keySet将键存储到Set集合Set<Student> studentSet = hp.keySet();System.out.println("\n调用hp集合方法:keySet方法,用Iterator迭代取出key:");Iterator<Student> studentIt = studentSet.iterator();while(studentIt.hasNext()) {Student studentKey = studentIt.next();String value = hp.get(studentKey);System.out.println("\t"+studentKey+"的地址:"+value);}System.out.println("\n调用hp集合方法:keySet方法,用for···each循环取出key:");for(Student stuSet : hp.keySet()) {Student studentKey = stuSet;String value = hp.get(studentKey);System.out.println("\t"+studentKey+"的地址:"+value);}}}

输出结果:

Java——(1)定义一个学生类Student 包含属性:姓名(String name) 年龄(int age) (2)定义Map集合 用Student对象作为key

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。