Search code examples
valalibgee

How to compare objects in Vala?


I am using a Gee.ArrayList with an own class for content. I want to use the "contains" method of the ArrayList, but I really don't know how to set up an equals-method in my class, so ArrayList uses it to find out if the object is in the ArrayList or not.

Example:

class Test : GLib.Object {
    public int number;
    
    public Test(int n) {
        number = n;
    }
    public bool equals (Test other) {
        if (number == other.number) return true;
        return false;
    }
}

Then, in another file:

var t = new Gee.ArrayList<Test>();
var n1 = new Test(3);
var n2 = new Test(3);
t.add(n1);
t.contains(n2); // returns false, but I want it to return true

Does anybody know that?


Solution

  • When you create the ArrayList, the constructor takes your equality comparator. You can do:

    var t = new Gee.ArrayList<Test>(Test.equals);
    

    and the contains should work as you desire.