java129-hashmap的方法
2022/6/26 1:24:36
本文主要是介绍java129-hashmap的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.util.Date;
public class Car {
private String brand;//品牌
private Date createDate;
private int housepower;//马力
private int speed;//速度
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public void setHousepower(int housepower) {
this.housepower = housepower;
}
public int getHousepower() {
return housepower;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
}
测试类
import java.util.*;
public class test68 {
public static void main(String[] args) {
Car c0 = new Car();
c0.setBrand("宝马");
c0.setCreateDate(new Date());
c0.setHousepower(4);
c0.setSpeed(200);
Car c1 = new Car();
c1.setBrand("创奇");
c1.setCreateDate(new Date());
c1.setHousepower(5);
c1.setSpeed(220);
Car c2 = new Car();
c2.setBrand("发力");
c2.setCreateDate(new Date());
c2.setHousepower(4);
c2.setSpeed(240);
Car c3 = new Car();
c3.setBrand("丰田");
c3.setCreateDate(new Date());
c3.setHousepower(4);
c3.setSpeed(230);
//Car c4 = c3;
// c4.setBrand("大众");
//c4.setCreateDate(new Date());
//c4.setHousepower(4);
//c4.setSpeed(230);
//添加hashmap的对象
Map carMap = new HashMap();
//使用put添加对象
carMap.put("k1", c0);
carMap.put("k2", c1);
carMap.put("k3", c2);
carMap.put("k4", c3);
//carMap.put("k4",c4);
//使用get返回自己需要的值
Object obj = carMap.get("k4");
if (obj != null) {
Car target = (Car) obj;
System.out.println(target.getBrand() + target.getHousepower());
} else {
System.out.println("未找到");
}
/*获取map集合的所有值*/
Set keySet = carMap.keySet();
Car c = null;
for (Object k : keySet) {
Car temp = (Car) carMap.get(k);
System.out.println(temp.getBrand() + temp.getHousepower() + temp.getSpeed());
}
/*获取所有值对象*/
Collection coll = carMap.values();
for (Object v : coll) {
System.out.println(((Car) v).getBrand());
}
/*判断是否包含某个给定的key*/
boolean boo = carMap.containsKey("k9");
System.out.println("是否包含k9" + boo);
System.out.println(carMap.containsValue(c3));
/*移除键值对象*/
if (carMap.containsKey("k3")) {
Object removeobj = carMap.remove("k3");
System.out.println(((Car) removeobj).getBrand());
}
System.out.println(carMap.size());
}
}
运行结果
这篇关于java129-hashmap的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略