Java.Util.Set does not add new elements

Asked

Viewed 52 times

-1

In the store variable when trying to add a new element of type "Store" it always stays with only one element and does not add a new element. And never add a new one. Follow the codes: Metodo main:

public static void main(String[] args) {
        Usuario usuario = new Usuario();
        Set<Integer> idsLojas = new HashSet<>();
        idsLojas.add(123);
        idsLojas.add(333);
        idsLojas.add(3333);

        Set<Loja> lojas = new HashSet<>();
        for (Integer idLoja : idsLojas) {
            lojas.add(new Loja(idLoja));
        }
        usuario.setLojas(lojas);

        System.out.println(usuario.getLojas().size());
    }

Shop builder:

public Loja(Integer id) {
        this.setId(id);

    }

The result is always 1, even if I add 3 values.

  • And the local variable lojas, has only one element?

1 answer

1


  • 2

    Maybe the problem is in Usuario: the setLojas or the getLojas may be fooling around. There is no guarantee of this as the code has not been shown

  • 2

    I don’t know if that’s the problem, because without overwriting equals and hashCode the code already works (creates a Set with 3 shops): https://ideone.com/fkd5Fy - se o Set of it is with 1 element, the problem may be elsewhere (or else he implemented equals and hashcode in the wrong way, that would explain the Set be with only 1 element: https://ideone.com/hfprQ3)

  • 1

    Taking advantage, the implementation of hashCode java normally makes 2 different objects have codes for hash distinct, and the equals means validated by the object reference (not the content, since the same reference implies even content) [this comment is basically @hkotsubo’s, but I started writing it before seeing that hkotsubo had commented]

  • 1

    @Jeffersonquesado You’re right. I wasn’t aware that Object.equals() should be enough to compare Store instances on Set. So forget everything I said (or not, it’s good to know).

  • The error was happening because of the hashcode and equals, because the set, the list, was recognizing as duplicate objects.

  • 1

    I didn’t get to understand what happened to "set recognize as duplicate objects", but if it helped, beauty. :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.