带遍历
public class Test4 {
public static void main(String[] args) {
HashMap<Phone,String> map = new HashMap<>();
map.put(new Phone("Apple",7000),"美国");
map.put(new Phone("Sony",5000),"日本");
map.put(new Phone("Huawei",6000),"中国");
Set<Phone> phones = map.keySet();
Iterator<Phone> iterator = phones.iterator();
while (iterator.hasNext()){
Phone next = iterator.next();
System.out.println(next.getBrand()+"=="+next.getPrice()+"=="+map.get(next));
}
}
}
class Phone{
private String Brand;
private int Price;
public Phone(String brand, int price) {
Brand = brand;
Price = price;
}
public String getBrand() {
return Brand;
}
public void setBrand(String brand) {
Brand = brand;
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
}
public class MapDemo {
public static void main(String[] args) {
//创建Map对象
Map<String, String> map = new HashMap<String,String>(); //数据采用的哈希表结构
//给map中添加元素
map.put("星期一", "Monday");
map.put("星期日", "Sunday");
System.out.println(map); // {星期日=Sunday, 星期一=Monday}
//当给Map中添加元素,会返回key对应的原来的value值,若key没有对应的值,返回null
System.out.println(map.put("星期一", "Mon")); // Monday
System.out.println(map); // {星期日=Sunday, 星期一=Mon}
//根据指定的key获取对应的value
String en = map.get("星期日");
System.out.println(en); // Sunday
//根据key删除元素,会返回key对应的value值
String value = map.remove("星期日");
System.out.println(value); // Sunday
System.out.println(map); // {星期一=Mon}
}
}