一、hashsetadd方法
public boolean add(E e)
HashSet類中的add方法是用來向集合中添加元素的,如果添加成功則返回true,否則返回false。
代碼示例:
HashSet 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("添加失敗"); }
二、hashsetadd方法怎麼自定義日期選取
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 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 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); } } }
三、與hashsetadd相關的其他方法
1、hashsetremove
public boolean remove(Object o)
HashSet類中的remove方法是用來從集合中刪除指定元素,如果刪除成功則返回true,否則返回false。
代碼示例:
HashSet hashSet = new HashSet(); hashSet.add("apple"); hashSet.add("banana"); hashSet.add("orange"); if(hashSet.remove("apple")){ System.out.println("刪除成功"); }else{ System.out.println("刪除失敗"); }
2、hashsetcontains
public boolean contains(Object o)
HashSet類中的contains方法是用來判斷集合中是否包含指定元素,如果包含則返回true,否則返回false。
代碼示例:
HashSet hashSet = new HashSet(); hashSet.add("apple"); hashSet.add("banana"); hashSet.add("orange"); if(hashSet.contains("apple")){ System.out.println("包含該元素"); }else{ System.out.println("不包含該元素"); }
3、hashsetclear
public void clear()
HashSet類中的clear方法是用來清空集合中所有元素。
代碼示例:
HashSet hashSet = new HashSet(); hashSet.add("apple"); hashSet.add("banana"); hashSet.add("orange"); hashSet.clear(); System.out.println("集合已清空");
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/183311.html