Add item only once in custom ArrayList

后端 未结 3 567
春和景丽
春和景丽 2021-01-23 08:28

I\'ve made my own custom ArrayList like this:

public class Points {
    String hoodName;
    Double points;
    Integer hoodId;
    public Points(String hN, Doub         


        
3条回答
  •  滥情空心
    2021-01-23 09:27

    In this case the Points object use default equals() method which is inconsistent. As you want to use contains method, you should implement equals() method like this way.

    public class Points {
    
        String hoodName;
        Double points;
        Integer hoodId;
    
        public Points(String hN, Double p, Integer hI) {
            hoodName = hN;
            points = p;
            hoodId = hI;
        }
    
        public Double getPoints() {
            return points;
        }
    
        public Integer getHoodId() {
            return hoodId;
        }
    
        public String getHoodName() {
            return hoodName;
        }
    
    
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof Points)) {
                return false;
            }
            Points points = (Points) obj;
    
            return points.getHoodName().equals(getHoodName().trim()) &&
                    points.getHoodId() == getHoodId()
                    && points.getPoints() == getPoints();
    
    
          }
    
        }
    

    If you ovverride equals() method, you can easily use it in ArrayList. Hope it will work in your case.

提交回复
热议问题