各位程序员,大家好。
所以我正在创建一个程序,允许用户指定他们想要的保险类型作为保险单的一部分。
由于只有 4 种类型的封面可供选择,我想使用集合或哈希集来跟踪向用户提供的封面类型。
问题是,它似乎没有消除重复项,它像数组列表一样对待它,当我打印出集合的内容时,我得到了不应该在集合中发生的重复项。
这是我用来将创建的保险类型对象传递给保险单类的代码。在实例化它们之后。
CoverType theInsuranceType = new CoverType("Fire",250);
theInsurancePolicy.includeCover(theInsuranceType);
这是我在保险单类中使用的代码,用于跟踪用户购买的保险类型。
import java.util.*;
// Class: InsurancePolicy
// Purpose: To represent a particular customer's insurance agreement
public class InsurancePolicy {
//ArrayList<Product> orderList = new ArrayList<Product>();
private static int totalPolicyCost;
private static String name = null;
private static int price = 0;
private int amount = 0;
private static int total = 0, claims = 0;
private static Set<CoverType> TheCoverType = new HashSet<CoverType>();
public static boolean includeCover(CoverType which)
{
TheCoverType.add(which);
System.out.println(which.getName()+" Has ben added to your insurance policy");
System.out.println(" ");
System.out.println(" ");
System.out.println("-----------------------");
return true;
}
我已经将其作为保险单类的一部分来完成,以迭代集合并为用户提取和打印每个对象的值,这就是我获得重复项的地方。
Iterator<CoverType> iter = TheCoverType.iterator();
int cash =0;
while (iter.hasNext())
{
CoverType type = iter.next();
cash = type.getPrice();
amount = amount + cash;
System.out.println("This one Cost. "+ cash);
// int cost = TheCoverType.getPrice().next();
// if theCover
}
amount = amount+ 100;
String message = "So all up total cost of the policy is. "+cash;
return amount;
任何帮助将不胜感激。
最佳答案
关于java - 为什么我的 Set 在 Java 编程中充当数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439640/