Java教程

Java HashSet add()

add()是Java HashSet类的一种方法,如果该集合将指定的元素添加到该集合中不包含任何元素。如果已经包含该元素,则调用将使集合保持不变并返回false。

语法

以下是 add()声明的方法:
public boolean add(E e)

参数

参数 说明 必需/可选
e 这是将添加到此集合中的元素。 必需

返回

如果此集合尚未包含指定的 true 方法,则 add()方法将返回 true

异常

NA

兼容版本

Java 1.2及更高版本

示例1

import java.util.*;
public class HashSetAddExample1 {
    public static void main(String[] args) {
        HashSet<String> set=new HashSet<String>();
        set.add("Ravi");
        set.add("Vijay");
        set.add("Ravi");
        set.add("Ajay");
        //Traversing elements Iterator<
        String>
        itr=set.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}
输出:
Vijay
Ravi
Ajay

示例2

import java.util.*;
public class HashSetAddExample2 {
    public static void main(String[] args) {
        HashSet<Integer> hset = new HashSet<Integer>();
        hset.add(121);
        hset.add(111);
        hset.add(151);
        System.out.println("Hash set Elements: "+ hset);
    }
}
输出:
Hash set Elements: [151, 121, 111]

示例3

import java.util.*;
public class HashSetAddExample3 {
    public static void main(String[] args) {
        HashSet<String> hashset1 = new HashSet<String>();
        HashSet hashset1.add("Facebook");
        hashset1.add("Twitter");
        hashset1.add("Instagram");
        boolean flag = hashset1.add("Google");
        System.out.println("Is the insertion successful?? - "+flag);
        System.out.println("Elements of the HashSet:");
        for(String val : hashset1) {
            System.out.println(val);
        }
    }
}
输出:
Is the insertion successful?? - true
Elements of the HashSet:
Google
Twitter
Instagram
Facebook

示例4

import java.util.*;
class Book {
    int id;
    String name,author,publisher;
    int quantity;
    public Book(int id, String name, String author, String publisher, int quantity) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.quantity = quantity;
    }
}
public class HashSetAddExample4 {
    public static void main(String[] args) {
        HashSet<Book> set=new HashSet<Book>();
        Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
        Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
        Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
        HashSet set.add(b1);
        set.add(b2);
        set.add(b3);
        for(Book b:set){
            System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
        }
    }
}
输出:
103 Operating System Galvin Wiley 6
102 Data Communications & Networking Forouzan Mc Graw Hill 4
101 Let us C Yashwant Kanetkar BPB 8

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4