详解hashsetadd方法

发布时间:2023-05-17

一、hashset add方法

public boolean add(E e)

HashSet类中的add方法是用来向集合中添加元素的,如果添加成功则返回true,否则返回false。 代码示例:

HashSet<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
// contains方法判断集合中是否包含某一元素,可以用来验证add是否成功
if(hashSet.contains("apple")){
    System.out.println("添加成功");
}else{
    System.out.println("添加失败");
}

二、hashset add方法怎么自定义日期选取

HashSet类中的add方法并不适用于自定义日期选取,但可以通过自定义对象实现此功能。 首先,自定义一个日期对象:

public class MyDate {
    private int year;
    private int month;
    private int day;
    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyDate myDate = (MyDate) o;
        return year == myDate.year &&
                month == myDate.month &&
                day == myDate.day;
    }
    @Override
    public int hashCode() {
        return Objects.hash(year, month, day);
    }
}

其中,equals方法用来判断两个对象是否相等,而hashCode方法用来计算对象的哈希值,以便于集合进行元素的存储和查找。在自定义对象中,要同时重写这两个方法,否则无法正常使用。 然后,通过自定义对象实现HashSet自定义日期选取的功能:

HashSet<MyDate> hashSet = new HashSet<>();
MyDate date1 = new MyDate(2021, 7, 19);
MyDate date2 = new MyDate(2021, 7, 20);
MyDate date3 = new MyDate(2021, 7, 21);
hashSet.add(date1);
hashSet.add(date2);
hashSet.add(date3);

代码示例:

public class Main {
    public static void main(String[] args) {
        HashSet<MyDate> hashSet = new HashSet<>();
        MyDate date1 = new MyDate(2021, 7, 19);
        MyDate date2 = new MyDate(2021, 7, 20);
        MyDate date3 = new MyDate(2021, 7, 21);
        hashSet.add(date1);
        hashSet.add(date2);
        hashSet.add(date3);
        //遍历集合中所有元素
        for (MyDate date : hashSet) {
            System.out.println(date.year + "-" + date.month + "-" + date.day);
        }
    }
}

三、与hashset add相关的其他方法

1、hashset remove

public boolean remove(Object o)

HashSet类中的remove方法是用来从集合中删除指定元素,如果删除成功则返回true,否则返回false。 代码示例:

HashSet<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
if(hashSet.remove("apple")){
    System.out.println("删除成功");
}else{
    System.out.println("删除失败");
}

2、hashset contains

public boolean contains(Object o)

HashSet类中的contains方法是用来判断集合中是否包含指定元素,如果包含则返回true,否则返回false。 代码示例:

HashSet<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
if(hashSet.contains("apple")){
    System.out.println("包含该元素");
}else{
    System.out.println("不包含该元素");
}

3、hashset clear

public void clear()

HashSet类中的clear方法是用来清空集合中所有元素。 代码示例:

HashSet<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
hashSet.clear();
System.out.println("集合已清空");