-2

How to check to see if an object with this name already exists in the List?

    @PostMapping
public String add(@RequestBody Produto item){
    if(produtos.contains(item) == ){
        return existente;
    } 
        produtos.add(item);
        return item.getNomeProduto();
    }
}
Efipee
  • 15
  • 5

1 Answers1

-1

As mentioned by shmosel, .contains() only works when equals() and hashCode() methods implemented correctly.
If such question appeared, it would be nice to you google and read more about these methods. For example
Overriding the java equals() method - not working?
Why do I need to override the equals and hashCode methods in Java?
In short, equals() tells java how to compare your objects
hashCode() tells how to generate the hashcode! It used by some algorythms or data structures like Set or Map to keep objects and allows to search objects faster within the data structure

Little hint, often your IDE can generate equals() and hashCode() methods for you.
For example in IntellijIdea you can open Produto class and press alt-insert -> equals() and hashCode()