0

here is my function

private static List<Types> getShiftTypes() {

    List<Types> types = new ArrayList<>();

    for (String shift : shifts_arr_t) {

        if (!types.contains(shift)) {

            types.add(new Types(shift));
        }

    }

    return types;
}

Types:

public class Types 
{
String type;
int count;

public Types(String type) {

        this.type = type;

}

@Override
public boolean equals(Object object)
{
    boolean sameSame = false;

    if (object != null && object instanceof Types)
    {
        sameSame = this.type == ((Types) object).type;
    }

    return sameSame;
}
}

But the compare override is not working. Can you please help me with that?

Dim
  • 4,527
  • 15
  • 80
  • 139
  • 1
    You have two mistakes in your implementation: you check `String`s for reference equality, and you override `equals` without overriding `hashCode`. – Sergey Kalinichenko Apr 16 '18 at 13:47

1 Answers1

2

You cannot compare bananas and apples.

Here :

    if (!types.contains(shift)) {

types refers to a List of Type and shift refers to a String.
Besides to make it working your equals() method should compare a String with a Type. Which is not a good idea as it could never be reflexive.

In your case, you don't need to override equals()/hashCode(), create instead of a method that iterates on types and return true or false according to the String to test equals to the Type field value of any elements in types.
Or as a straighter alternative use a stream with a Predicate such as :

private static List<Types> getShiftTypes() {

    List<Types> types = new ArrayList<>();

    for (String shift : shifts_arr_t) {

        if (types.stream().anyMatch(t -> t.getType().equals(shift))) {    
            types.add(new Types(shift));
        }

    }

    return types;
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215