package Hard.Map_;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapExercise {
@SuppressWarnings({"all"})
public static void main(String[] args) {
HashMap hashmap = new HashMap();
hashmap.put(1,new Employee("jack",1,2000));
hashmap.put(2,new Employee("justin",2,2400));
hashmap.put(3,new Employee("amy",3,2080));
//使用keySet -> 增强for循环
Set set = hashmap.keySet();
for (Object key : set) {
Employee emp = (Employee) hashmap.get(key);
/*由于hashmap.get(key)方法的返回类型是Object,而期望的类型是Employee,
所以需要将返回的对象强制转换为Employee类型。如果不进行强制转换,编译器会认为
返回的是一个Object类型的对象,无法调用Employee对象的方法。
* */
if (emp.getSal()>2300){
System.out.println(emp);
}
}
//使用EntrySet -> 迭代器
Set entryset = hashmap.entrySet();
Iterator iterator = entryset.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
//通过entry取得key 和 value
Employee emp = (Employee) entry.getValue();
if (emp.getSal() > 2300){
System.out.println(emp);
}
}
}
}
class Employee{
private String name;
private int id;
private double sal;
public Employee(String name, int id, double sal) {
this.name = name;
this.id = id;
this.sal = sal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", id=" + id +
", sal=" + sal +
'}';
}
}
Java_Map练习
最新推荐文章于 2024-07-27 13:31:57 发布