有如下人员数据
名字 年龄 地址 工资
张三丰 18 春熙路, 6000
赵云 19 天府广场 8000
张辽 20 布鲁明顿 9000
张飞 20 布鲁明顿 9000
1、定义一个Person类,要求person每一个对象存储一个人的( 名字 年龄 地址)数据。
2、创建perosn对象表示上述的( 名字 年龄 地址)数据,并添加到map中存储
(key用person对象,value用(工资))
3、
a)把map容器对象中键为(赵云 19 天府广场)的值【工资】增加5000元。
b)把键为( 张辽 20 布鲁明顿)的键值对删除,
再检查是否有( 张辽 20 布鲁明顿)这个键的键值对是否存在
4、两种方式打印map中所有人的【名字】和【工资】
名字 年龄 地址 工资
张三丰 18 春熙路, 6000
赵云 19 天府广场 8000
张辽 20 布鲁明顿 9000
张飞 20 布鲁明顿 9000
1、定义一个Person类,要求person每一个对象存储一个人的( 名字 年龄 地址)数据。
2、创建perosn对象表示上述的( 名字 年龄 地址)数据,并添加到map中存储
(key用person对象,value用(工资))
3、
a)把map容器对象中键为(赵云 19 天府广场)的值【工资】增加5000元。
b)把键为( 张辽 20 布鲁明顿)的键值对删除,
再检查是否有( 张辽 20 布鲁明顿)这个键的键值对是否存在
4、两种方式打印map中所有人的【名字】和【工资】
5、一种方式求出map中所有人的【平均工资】
import java.util.Map;
import java.util.Set;
import java.util.Collection;
import java.util.HashMap;
public class Test2 {
public static void main(String[] args) {
Map<Person,Integer> map=new HashMap<Person,Integer>();
map.put(new Person("张三丰",18,"春熙路"), 6000);
map.put(new Person("赵云",19,"天府广场"), 8000);
map.put(new Person("张辽",20,"布鲁明顿 "), 9000);
map.put(new Person("张飞 ",20,"布鲁明顿 "), 9000);
System.out.println(map);
Integer newSal=map.get(new Person("赵云",19,"天府广场"))+5000;
map.put(new Person("赵云",19,"天府广场"), newSal);
System.out.println("工资增加后的数据:"+map);
map.remove(new Person("张辽",20,"布鲁明顿 "));
System.out.println("张辽还存在吗?"+map.containsKey(new Person("张辽", 20, "布鲁明顿")));
System.out.println("删除后的内容:"+map);
Set<Person> keySet=map.keySet();
for(Person key :keySet){
System.out.println("名字:"+key.name+" 工资:"+map.get(key));
}
System.out.println("第二种遍历:");
Set<Map.Entry<Person, Integer>> entrySet=map.entrySet();
//遍历所有的键值对
for (Map.Entry<Person, Integer> entry : entrySet) {
String name=entry.getKey().name;
Integer sal=entry.getValue();
System.out.println("名字:"+name+" 工资:"+sal);
}
Collection<Integer> values= map.values();
int sumSal=0;
for (Integer sal : values) {
sumSal+=sal;
}
int avgSal=sumSal/map.size();
System.out.println("平均工资:"+avgSal);
}
}
class Person{
String name;
int age;
String addr;
public Person(String name, int age, String addr) {
super();
this.name = name;
this.age = age;
this.addr = addr;
}
@Override
public String toString() {
return "\nPerson [name=" + name + ", age=" + age + ", addr=" + addr + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addr == null) ? 0 : addr.hashCode());
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (addr == null) {
if (other.addr != null)
return false;
} else if (!addr.equals(other.addr))
return false;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}