为什么我在Java编程中作为数组列表工作?

Bin*_*min 0 java set

各位程序员再次问好.

所以我正在创建一个程序,允许用户指定他们想要的保险类型作为保险单的一部分.

由于它们只有4种类型的封面可供选择,我想使用一套或散列集来跟踪提供给用户的封面类型.

问题是,似乎没有摆脱重复,它正在将它视为arraylist,当我打印出集合的内容时,我得到重复,这不应该发生在集合中.

这是我用来将创建的保险类型对象传递给保险单类的代码.在实例化之后.

CoverType theInsuranceType = new CoverType("Fire",250);
theInsurancePolicy.includeCover(theInsuranceType);
Run Code Online (Sandbox Code Playgroud)

这是我在保险单类中使用的代码,用于跟踪用户已采取的保险类型.

    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;

        }
Run Code Online (Sandbox Code Playgroud)

我已经做了这个作为保险政策类的一部分来迭代集合并为用户拉出并打印每个对象的值,这就是我得到重复的地方.

    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;
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Ste*_*all 5

要放入集合中的对象需要实现equalshashcode.

即使所有字段都"相等",.equals()除非重写这些方法,否则不会在java中获得对象equality().