Map接口_HashMap常用的方法

本文通过具体实例展示了Java中HashMap的使用方法,包括增删查改、键值对的存储和检索,以及如何处理键冲突导致的值更新。同时,介绍了泛型在Map中的应用,演示了如何存储自定义类的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Map;

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

/**
* 测试HashMap的使用
*/
public class TestMap {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<>();
//增加
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
//获取
System.out.println(map.get(1));
System.out.println(map.size());
System.out.println(map.isEmpty());
System.out.println(map.containsKey(1));
System.out.println(map.containsValue("four"));

Map<Integer,String> m1=new HashMap<>();
m1.put(4,"four");
map.putAll(m1);
System.out.println(map);
//map中键不能重复,如果重复(是否重复根据equals方法),新的值会覆盖旧的值
map.put(3,"five");
System.out.println(map);
}
}

二、泛型时对象
package Map;

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

public class TestMap2 {
public static void main(String[] args) {
Map<Integer,Student> m1=new HashMap<>();
m1.put(1001,new Student(10001,"小明",3000));
Student s1=m1.get(1001);
System.out.println(s1.getName());
}
}




class Student{
int id;
String name;
int salary;

public int getId() {
return id;
}

public int getSalary() {
return salary;
}

public String getName() {
return name;
}
public Student(int id,String name,int salary){
this.id=id;
this.name=name;
this.salary=salary;
}

@Override
public String toString() {
return "id"+id+"名字"+name+"薪水"+salary;
}
}


转载于:https://www.cnblogs.com/zzzao/p/11012894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值