Home > Enterprise >  in Android java, how can I remove duplicate items in a list?
in Android java, how can I remove duplicate items in a list?

Time:11-24

@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
    if (task.isSuccessful()) {
        for (QueryDocumentSnapshot collections : queryDocumentSnapshots) {

            Booking booking = collections.toObject(Booking.class);
            bookingList.add(booking);

            //bookingList.add(booking);


        }

I tried using bookingList.distinctive, and a HashSet but couldn' get anything to work

CodePudding user response:

While using HashSet have you overriden hashcode and equals method in Booking class ?

Check this out - https://www.baeldung.com/java-equals-hashcode-contracts

Your Booking class will have some variables. Use those variables to write your custom overriden equals and hashcode methods.

Default implementation of equals method uses memory location or address to find equality. Two objects even though having same variable(fields inside object) values, will not be equal in default equal method as they differ in memory address.If all the variables are equal in two objects then equals method should return true and generate same hashcode also in overriden hashcode method. hashcode method should use those variables to generate hashcode. If you will not override hashcode method, default hashcode value will be used and in that case two equal objects might return different hashcode.

  • Related