I have a List at java. My class has fields and one of them is: name. Lets assume that:
List<MyClass> mylist = new ArrayList<MyClass>();
MyClass myElement = new MyClass();
myElement.setName("xxx");
So how can I check is there any element at List which contains same name with myElement variable and retrieve that variable?
If your
MyClassimplementsequals()in a way that makes twoMyClassinstances equal if they have the same name, then you can simply do:Unfortunately there is no “get the element that is
equal()to this” method in theCollection/ListAPI, which could be implemented in a more efficient manner.If you don’t have such a
equals()implementation (or don’t want it for some reason), then you’ll have to do it the boring, old-fashioned way: