Home >Java >javaTutorial >How to use add in java
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.
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"><code class="java">boolean add(E element);</code></pre>
Among them,
is The type of element in the collection, element
is the element to be added to the collection.
add()
The method returns a Boolean value to indicate whether the element was successfully added to the collection:
If the element is already contained in the set, return Set
collection) or do nothing (for the List
collection) .
For List collection
<code class="java">List<String> names = new ArrayList<>();
names.add("John"); // 添加元素 "John" 到列表
names.add("Mary"); // 添加元素 "Mary" 到列表</code>
<code class="java">Set<Integer> numbers = new HashSet<>();
numbers.add(1); // 添加元素 1 到集合
numbers.add(2); // 添加元素 2 到集合
numbers.add(1); // 不会添加到集合中,因为集合中已存在该元素</code>
For
For the add()
method will return false
, but will not throw an exception .
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!