I
I
iscateli2021-12-20 23:41:08
Java
iscateli, 2021-12-20 23:41:08

Do collections allow duplication?

Why is it written in the book "Horstmann K. - Java. The Professional's Library, Volume 1" that the collection does not allow duplication of objects? Does this apply to any collection that implements the Collection interface? Or some specific implementation? I specifically quoted the entire section 9.1.2., even from the context it is not clear what is meant.

9.1.2. The Collection Interface
At the heart of the collection classes in the Java library is the
Collection interface. It includes two main methods:
public interface Collection<E>
{
  boolean add(E element);
  Iterator<E> iterator();
}

In addition to these, there are several other methods discussed later in this
chapter. The add() method adds an element to the collection. It returns a boolean true if the addition of the element actually changed the collection, or
a boolean false if the collection remained unchanged. For example, if you try to add an object to a collection where such an object already exists, calling the add() method will not give the desired result, since the collection does not allow duplicate objects. And the iterator() method returns an object of a class that implements the
Iterator interface. An iterator object can be chosen to access all elements of the collection
in turn. Iterators are discussed in more detail in the next section.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-12-21
@iscateli

There are some collections (not all) that do not allow duplicates - it is for them that the variant is possible when the .add method returns false.
Documentation https://docs.oracle.com/javase/8/docs/api/java/uti... :

Returns false if this collection does not permit duplicates and already contains the specified element.

Returns false if this collection does not allow duplicates and already contains the given element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question