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

How to use add in java

下次还敢
Release: 2024-04-21 02:18:34
Original
660 people have browsed it

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: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>boolean add(E element);</pre><div class="contentsignin">Copy after login</div></div>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

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

For Set collection

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

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template