java HashSet的使用

今天在寫代碼時想要使用HashSet,因爲以前並不瞭解,就在網上查了一下原理及使用方法。java

HashSet原理數據庫

  該類實現了Set接口,HashSet中不容許元素重複,不保證集合中元素的順序,元素可爲null,但最多隻能一個。對於 HashSet 而言,HashSet繼承自AbstractSet,它是基於 HashMap 實現的,HashSet 底層使用HashMap來保存全部元素。所以HashSet的實現比較簡單,相關 HashSet 的操做,基本上都是直接調用底層 HashMap 的相關方法來完成。ssh

經常使用方法spa

  構造方法:code

    默認構造器:對象

public HashSet() { map = new HashMap<>(); }

    將傳入的集合添加到HashSet的構造器blog

public HashSet(Collection< ? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); }

    明確初始容量和裝載因子的構造器繼承

public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<>(initialCapacity, loadFactor)
}

    僅明確初始容量的構造器(裝載因子默認0.75接口

public HashSet(int initialCapacity) { map = new HashMap<>(initialCapacity); }

    API中幾個經常使用方法:ci

    size() :返回值爲int,返回此 set 中的元素的數量(set 的容量)。

    isEmpty():返回值爲boolean, 若是此 set 不包含任何元素,則返回 true。

    add(E e):返回值爲boolean,若是此 set 中還沒有包含指定元素,則添加指定元素。

    iterator():返回值爲Iterator<E>, 返回對此 set 中元素進行迭代的迭代器。

    remove(Object o):返回值爲boolean,若是指定元素存在於此 set 中,則將其移除。

    contains(Object o):返回值爲boolean,若是此 set 包含指定元素,則返回 true。

    clear():無返回值, 今後 set 中移除全部元素。

    clone():返回值爲Object,返回此HashSet的淺表副本,而並無複製元素自己。

 

HashSet的簡單使用

建立:

package com.cmq.common; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.cmq.entity.Shoes; import com.cmq.entity.Manager; /** *@author chenmeiqi *@version 2020年2月10日 下午3:33:08 *@公共屬性類 */
public class Constants { //使用List模擬數據庫,建立管理員List對象 //public static List<Manager> mgrlist = new ArrayList<>();
    
    public static Set<Shoes> hashsetShoes= new HashSet<>(); }

添加

if (idyz(Integer.parseInt(s[0]))) { if (Util.isEmpty(s[1])) { if (s[6].equals("1") || s[6].equals("2") || s[6].equals("3") || s[6].equals("4")) { shoe.setId(Integer.parseInt(s[0])); shoe.setName(s[1]); shoe.setSign(Integer.parseInt(s[6])); shoe.setImage(s[2]); shoe.setPrice(Double.parseDouble(s[3])); shoe.setPub_address(s[4]); shoe.setPub_date(Util.StringToDate(s[5])); // 保存set集合中
 Constants.hashsetShoes.add(book); } else { System.out.println("*******類別輸入有誤!****"); } } else { System.out.println("*******名稱不能爲空!*****"); } }

刪除:

for(Shoesshoes:Constants.hashsetShoes) { if(shoes.getId() == id_input) {//從hashsetShoes中查詢出id爲傳入的id的用戶
                Constants.hashsetBook.remove(shoes);//刪除該商品
                break; } }
相關文章
相關標籤/搜索