0

in my android app, i would like to check, if a value is already in my array list.

i tried something like this:

private List<Values> retrieve() {


        List<Values> list = new ArrayList<>();

        int x = 0;
        while (x < Values.length) {
            if (list.contains(new Values(Values[x]))) {
                Log.e("-->", "DUPLICATE: "+Values[x]);
            } else {
                Log.e("-->", "NEW: "+Values[x]);
                list.add(new Values(Values[x]));
            }
            x++;
        }
        return list;

    }

The content of my ArrayList "Values":

Max,Sabine,Chris,Max,Max

But i always get the Log "NEW". but this can't be right. The Value "Max" is an duplicate.

What is my mistake?

SpecialFighter
  • 573
  • 1
  • 9
  • 14
  • why you use new Values(Values[x]) ? why not use directly check with Values[x] – sasikumar Jan 11 '16 at 07:01
  • I think to get it work need to override `hashCode ` and `equals ` methods in `Values ` class. see following post http://stackoverflow.com/questions/8322129/arraylists-custom-contains-method probably help – ρяσѕρєя K Jan 11 '16 at 07:03
  • Why do you use List? Should be try set, map etc dictionary collections. If you will use list, you could creafully about object hashcode values. – nurisezgin Jan 11 '16 at 07:14

1 Answers1

0

Don't create a new object.

int x = 0;
while (x < Values.length) {
    if (list.contains(Values[x])) {
        Log.e("-->", "DUPLICATE: "+Values[x]);
    } else {
        Log.e("-->", "NEW: "+Values[x]);
        list.add(Values[x]);
    }
    x++;
}
return list;

But best would be to not allow duplicates to be stored. You can use a LinkedHashSet for that (if you want it ordered). Else just a HashSet would do fine.

RvdK
  • 19,580
  • 4
  • 64
  • 107