java - How do you check if a list contains an element that matches some predicate? -


i have arraylist containing objects have 4 parameters (x, y, id , mytype). want verify if there objects in arraylist have particular coordinates, independently of id , mytype parameters. wanted use arrays.aslist(yourarray).contains(yourvalue) when object has 1 parameter.

here whole code:

public class myobject {    public float x;   public float y;   public int id;   public string mytype;     public myobject (float x, float y, int id, string mytype)    {     this.mytype = mytype;     this.id = id;     this.x = x;     this.y = y;   }   @override     public string tostring() {     return ("[id="+id+" x="+x+" y="+y +" type="+mytype+"]");   } }   arraylist<myobject> myarraylist = new arraylist<myobject>();  void setup()  {   size(100, 60);   myarraylist.add(new myobject(3.5, 4.5, 6, "a"));   myarraylist.add(new myobject(5.4, 2.6, 4, "b")); } 

for example, if want verify if there object has coordinates (3.5, 4.5), how should proceed ? there easy way ?

thanks help

you can override equals function define equal:

public class myobject {      public float x;     public float y;     public int id;     public string mytype;       public myobject (float x, float y, int id, string mytype)     {         this.mytype = mytype;         this.id = id;         this.x = x;         this.y = y;     }     @override     public string tostring() {         return ("[id="+id+" x="+x+" y="+y +" type="+mytype+"]");     }      @override     public boolean equals(object o) {         if (o instanceof myobject) {             myobject myobject = (myobject) o;             return myobject.id == this.id && myobject.mytype.equals(this.mytype);         }          return false;     } } 

attention:

i must admit it's dangerous way this. override equals maybe cause strange issues in program if have used equals other compares. in special case, maybe can that.


Comments