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()); } }