0

My wrapper class is as follow:

   public class FilterWrapper implements Comparable {
        public String label {get; set;}
        public String value {get; set;}


        public Integer compareTo(Object compareTo) {
            FilterWrapper filterWrapper = (FilterWrapper) compareTo;
            if (label == filterWrapper.label) return 0;
            if (label > filterWrapper.label) return 1;
            return -1;        
        }

    }

I am using following code in apex.

resNameList type : List

resName type : FilterWrapper

if(!resNameList.contains(resName)) {                    
    resNameList.add(resName);
} else {
    Integer index = resNameList.indexOf(resName);
    resNameList.get(index).isShow = true;
} 

I want to compare FilterWrapper instance based on label.

But

resNameList.contains(resName)

Always return false even for same label.

What is the issue in this ? How can we fix it ?

  • 4
    Its probably equals you need to implement. – Keith C Mar 21 '18 at 13:00
  • 1
    yes, Comparable interface is used when there is a need to sort elements in List. Just wrong implemented interface :) – Oleksandr Berehovskyi Mar 21 '18 at 13:02
  • 1
    Don't forget about hashCode! And it's not really an interface, even though it should be. – Adrian Larson Mar 21 '18 at 13:18
5

The List.contains method works exactly like Set.contains. As mentioned in the comments, you need to implement equals and hashCode if you want to use custom types in this sort of comparison. Below is a simple test class to illustrate:

@IsTest
class Demo
{
    virtual class Foo
    {
        Integer x, y;
        Foo(Integer x, Integer y)
        {
            this.x = x;
            this.y = y;
        }
    }
    class Bar extends Foo
    {
        Bar(Integer x, Integer y) { super(x, y); }
        public Boolean equals(Object instance)
        {
            Bar that = (Bar)instance;
            return this.x == that.x;
        }
        public Integer hashCode()
        {
            return x;
        }
    }

    @IsTest static void testFoo()
    {
        List<Foo> wrappers = new List<Foo> { new Foo(1, 2) };
        system.assertEquals(false, wrappers.contains(new Foo(1, 2)));
    }
    @IsTest static void testBar()
    {
        List<Bar> wrappers = new List<Bar> { new Bar(1, 2) };
        system.assertEquals(true, wrappers.contains(new Bar(1, 2)));
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.