HashMap的遍历有两种方法,其中一种是keyset(),另一种是entryset(). 但entryset()的效率更高。
从下面这道java练习题学会entryset()的使用。
题目:
用HashMap模拟一个网上购物车。要求:从键盘输入n种书的名称、单价、购买数量,将这些信息存入一个HashMap,然后将该HashMap作为参数调用方法getSum(HashMap books),该方法用于计算书的总价并返回。【说明:键盘输入可使用Scanner类】<shuming, BOOK类>
package T2;
import java.util.*;
public class ShoppingCar {
public static double getSum(HashMap books){
double sum = 0;
Iterator iter = books.entrySet().iterator(); //注意配合上遍历
while(iter.hasNext()){
Map.Entry<String, Object> entry = (Map.Entry<String, Object>)iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
sum += ((BookNum)val).getMoney()*((BookNum)val).getNumber();
}
return sum;
}
public static void main(String[] args) {
HashMap<String,Object> mapBook = new HashMap<String,Object>();
Scanner sc = new Scanner(System.in);
System.out.println("请输入有几本书:");
int n = sc.nextInt();
for(int i = 0; i < n; i++){
System.out.println("请输入书名、单价、购买数量:");
String bookName = sc.next();
double moneyEach = sc.nextDouble();
int num = sc.nextInt();
mapBook.put(bookName, new BookNum(moneyEach, num));
}
System.out.println("书的总价钱为:" + getSum(mapBook));
}
}
class BookNum{
private double money;
private int number;
public BookNum(double moy, int num){
this.money = moy;
this.number = num;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}