加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

HashMap练习

发布时间:2021-05-20 09:43:32 所属栏目:大数据 来源: https://blog.csdn.net/summoxj
导读:Person类: public class Person { ?? ?private String name; ?? ?private int age; ?? ?public Person(String name,int age) { ?? ??? ?super(); ?? ??? ?this.name = name; ?? ??? ?this.age = age; ?? ?} ?? ?public Person() { ?? ??? ?super(); ?? ?} ?

Person类:

public class Person {
?? ?private String name;
?? ?private int age;
?? ?public Person(String name,int age) {
?? ??? ?super();
?? ??? ?this.name = name;
?? ??? ?this.age = age;
?? ?}
?? ?public Person() {
?? ??? ?super();
?? ?}
?? ?
?? ?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;
?? ?}
?? ?@Override
?? ?public String toString() {
?? ??? ?return "Person "+name+"...."+age;
?? ?}

}


测试Demo类:

import java.util.HashMap;
import java.util.Map;

//使用HashMap集合,存储自定义的对象
public class HashMapDemo {
?? ?public static void main(String[] args) {
?? ??? ?function_1();
?? ??? ?
?? ??? ?function_2();
?? ?}
?? ?
?? ?//HashMap 存储自定义的对象Person,作为值出现
?? ?//键的对象,是字符串,可以保证唯一性
?? ?public static void function_1(){
?? ??? ?HashMap<String,Person> map=new HashMap<String,Person>();
?? ??? ?map.put("beijing",new Person("a",20));
?? ??? ?map.put("shanghai",new Person("b",18));
?? ??? ?map.put("guangzhou",new Person("c",19));
?? ??? ?//keySet增强for遍历
?? ??? ?for(String key:map.keySet()){
?? ??? ??? ?Person value=map.get(key);
?? ??? ??? ?System.out.println(key+"...."+value);
?? ??? ?}
?? ??? ?//entrySet增强for遍历
?? ??? ?System.out.println("==============================");
?? ??? ?for(Map.Entry<String,Person> entry:map.entrySet()){
?? ??? ??? ?String key=entry.getKey();
?? ??? ??? ?Person value=entry.getValue();
?? ??? ??? ?System.out.println(key+"...."+value);
?? ??? ?}
?? ?}
?? ?
?? ?
?? ?//HashMap 存储自定义的对象Person,作为值出现
?? ?//键的对象,是Person类型,值是字符串
?? ?//保证键的唯一性,存储到键的对象,重写hashCode equals
?? ?public static void function_2(){
?? ??? ?HashMap<Person,String>map=new HashMap<Person,String>();
?? ??? ?map.put(new Person("a",20),"里约热内卢");
?? ??? ?map.put(new Person("b",18),"索马里");
?? ??? ?map.put(new Person("b","索马里");
?? ??? ?map.put(new Person("c",19),"百慕大");
?? ??? ?//keySet
?? ??? ?for(Person key:map.keySet()){
?? ??? ??? ?String value=map.get(key);
?? ??? ??? ?System.out.println(key+"...."+value);
?? ??? ?}
?? ??? ?//entrySet
?? ??? ?System.out.println("==========================");
?? ??? ?for(Map.Entry <Person,String> entry:map.entrySet()){
?? ??? ??? ?System.out.println(entry.getKey()+"...."+entry.getValue());
?? ??? ?}
?? ?}
}


(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读