基本类是学生类(属性 name,age)用Student对象作为Key,住址为值,创建Map集合使用HashMap,遍历方式:1,增强for循环(EntrySet) 2.增强for循环(keySet) 3.使用迭代器遍历(EntrySet) 4.使用迭代器遍历(keySet)- class Test01 {
- public static void main(String[] args) {
- // 1.定义HashMap集合,键为Student对象,值为String类型的对象,表示地址
- HashMap<Student, String> map = new HashMap<>();
- map.put(new Student("张三", 20), "北京");
- map.put(new Student("李四", 20), "南京");
- map.put(new Student("王五", 20), "上海");
- // 遍历方式一:增强for循环(entrySet)
- for (Map.Entry<Student, String> entry : map.entrySet()) {
- System.out.println(entry.getKey() + "=" + entry.getValue());
- }
-
- //遍历方式二:增强for循环(keySet)
- for(Student student :map.keySet()) {
- String address = map.get(student);
- System.out.println(student+"="+address);
- }
-
- // 遍历方式三:迭代器(通过entrySet())
- Set<Map.Entry<Student, String>> set = map.entrySet();
- Iterator<Map.Entry<Student, String>> it = set.iterator();
- while (it.hasNext()) {
- Map.Entry<Student, String> entry = it.next();
- System.out.println(entry.getKey() + "=" + entry.getValue());
- }
- // 遍历方式四:迭代器(通过keySet())
- Set<Student> keySet = map.keySet();
- Iterator<Student> it2 = keySet.iterator();
- while(it2.hasNext()) {
- Student student = it2.next();
- String address = map.get(student);
- System.out.println(student+"="+address);
- }
- }
- }
复制代码
|
|