Home >Java >javaTutorial >How to use add in java

How to use add in java

下次还敢
下次还敢Original
2024-04-21 02:18:34452browse

The add() method in Java is used to add elements to a collection. This method returns true to indicate successful addition, false to indicate that the element already exists in the collection (Set) or does not perform the operation (List). Usage is as follows: List: add(E element) Adds an element to the end of the list. Set: add(E element) Adds an element to the set, returning false if it exists.

How to use add in java

Usage of add in java

add() The method is Java## A method of a #Collection interface (such as List, Set) that is used to add elements to a collection.

Usage

##add()

The basic syntax of the method is as follows: <pre class="brush:php;toolbar:false">&lt;code class=&quot;java&quot;&gt;boolean add(E element);&lt;/code&gt;</pre>Among them,

E

is The type of element in the collection, element is the element to be added to the collection.

Return value

add()

The method returns a Boolean value to indicate whether the element was successfully added to the collection:

If the element is not yet contained in the collection,
    true
  • is returned. If the element is already contained in the set, return
  • false
  • (for the Set collection) or do nothing (for the List collection) .
Example

For List collection

<code class="java">List<String> names = new ArrayList<>();
names.add("John"); // 添加元素 "John" 到列表
names.add("Mary"); // 添加元素 "Mary" 到列表</code>

For Set collection

<code class="java">Set<Integer> numbers = new HashSet<>();
numbers.add(1); // 添加元素 1 到集合
numbers.add(2); // 添加元素 2 到集合
numbers.add(1); // 不会添加到集合中,因为集合中已存在该元素</code>

Notes

For
    List
  • collections, added elements will be added to the end of the list. For the
  • Set
  • collection, if the element already exists in the collection, the add() method will return false, but will not throw an exception .
  • add()
  • method is an optional operation and may throw UnsupportedOperationException when the collection does not support adding elements.

The above is the detailed content of How to use add in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn