简体   繁体   中英

SPRING Function to validate object not accepting type of data

I'm triying to make a function to validate if an object is inside a List of objects, but I have a problem, because I'm using a class to define the properties of the awaiting object, so in the IDE seems to give some help to solve the issue, but I don't want to do like that, my idea, is to make a function global, to validate any type of list, so this is my code, sorry if are not good, but is a try.
* The list and the object have the same class.

objExist(statusClaim, statusClaimRP) /*<=== Is just the function on my code for reference */

private Boolean objExist(List<Object> arreglo, Object objeto) throws JSONException {
 Integer valida = 0;
 for(Integer i = 0; i < arreglo.size(); i++) {
     if(arreglo.get(i) == objeto) {
         valida++;
     }  
 }
 if(valida > 0) {
     return false;
 } else {
     return true;
 }
}

The method objExist(List'<'Object'>', Object) in the type ClaimService is not applicable for the arguments (List'<'StatusClaimDTO'>', StatusClaimDTO).

As I understood you want to make sure that certain list contains certain object? If so you can use list.contains(objectToFind) or streams:

listOfSomeObjects.stream().anyMatch(obj -> obj.equals(objectToFind);

Alternatevely, for learning purposes, you can simply iterate over you list in for loop and wrap it into generic method:

private <T> boolean listContainsElement(List<T> list, T elementToFind) {
        for (T element: list) {
            if (element.equals(elementToFind)) {
                return true;
            }
        }
        return false;
    }

But it's not practical.

Note: == compares references, not objects themselves, which means if obj1 == obj2 that both variable point to the same instance of the object, if this is what you want then ok. But ussually objects are compared with equals method which you can override and use your own logic, otherwise it has default implementation that basically acts like == operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM