目录
3.往一个Map集合中添加若干元素。获取Map中的所有value,并使用增强for循环和迭代器遍历输出每个value。
4.使用Map集合存储自定义数据类型Car做键,对应的价格做值。并使用KeySet和entrySet两种方式遍历Map集合
1.请简述Map接口的特点
- Map每个元素由键和值两部分组成
- Map键不能重复,每个键对应一个值
- 键和值可以为null
2.说出Entry键值对对象遍历Map集合的原理
Map中存在的是两种对象,一种称Key(键),一种称value(值),它们在Map中是一一对应的关系,这一对对象又称作Map中的一个Entry(项)。Entry将键值对的对应关系封装成了对象,即键值对对象这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键和对应的值。
3.往一个Map集合中添加若干元素。获取Map中的所有value,并使用增强for循环和迭代器遍历输出每个value。
代码如下:
public class MapTest1 {
public static void main(String[] args) {
//创建HashMap
HashMap<String, String> map = new HashMap<>();
//put添加元素
map.put("湖北f1","hlz");
map.put("湖北f2","xyx");
map.put("湖北f3","szj");
//使用Map的values方法来获得所有的value
Collection<String> values = map.values();
//增强for循环
for (String value : values) {
System.out.println(value);
}
System.out.println("————");
//迭代器
Iterator iterator = values.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
执行结果如下:
4.使用Map集合存储自定义数据类型Car做键,对应的价格做值。并使用KeySet和entrySet两种方式遍历Map集合
首先建一个汽车类,包含名称和颜色属性,重写hashCode和equals方法。
代码入下:
public class Car {
private String name;
private String color;
public Car() {
}
public Car(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (color != null ? color.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Car)){
return false;
}
Car car = (Car) o;
if (!Objects.equals(name, car.name)){
return false;
}
return Objects.equals(color, car.color);
}
}
再建一个Test类,使用HashMapKey保存汽车对象,value是汽车价格
代码如下:
public class MapTest2 {
public static void main(String[] args) {
HashMap<Car,Integer> map = new HashMap<>();
Car c1 = new Car("布加迪威龙","黑色");
Car c2 = new Car("兰博基尼","白色");
Car c3 = new Car("法拉利","蓝色");
map.put(c1,10000000);
map.put(c2,8000000);
map.put(c3,5000000);
//使用KeySet方式遍历Map
Set<Car> KeySet = map.keySet();
for (Car c :KeySet) {
Integer value = map.get(c);
System.out.println(c.getName() + "," +c.getColor() + ",价格为:" + value);
}
System.out.println("————————————————————————————");
//使用entrySet方式遍历Map
Set<Map.Entry<Car,Integer>> entrySet = map.entrySet();
for (Map.Entry<Car,Integer> entry : entrySet) {
Car key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key.getName() + ","+ key.getColor() + ",价格为:" + value);
}
}
}
执行结果如下: