java128-map类
作者:互联网
定义一个汽车类
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.Date;
import java.util.HashMap;
import java.util.Map;
public class test67 {
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,Car,c3,Date,new,java128,public,carMap 来源: https://www.cnblogs.com/yao-655442/p/16411687.html