Core Java (二十三) 集(Set介面)

來源:互聯網
上載者:User

之前我寫過的一片博文講過了散列表(Hash Table),而散列表可以用來實現散列集(HashSet)和散列映射表(HashMap)。

HashSet

HashSet<T>類有四種建構函式:

Constructor and Description
HashSet()

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(Collection<?
extends E> c)

Constructs a new set containing the elements in the specified collection.
HashSet(int initialCapacity)

Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)

Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

它的全部方法:

Modifier and Type Method and Description
boolean add(E e)

Adds the specified element to this set if it is not already present.
void clear()

Removes all of the elements from this set.
Object clone()

Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)

Returns true if this set contains the specified element.
boolean isEmpty()

Returns true if this set contains no elements.
Iterator<E> iterator()

Returns an iterator over the elements in this set.
boolean remove(Object o)

Removes the specified element from this set if it is present.
int size()

Returns the number of elements in this set (its cardinality).
TreeSet

TreeSet為樹集,,是一個有序的集合( an sorted collection)。這個類按某個順序進行排序,實現用的是紅/黑樹狀結構。

建構函式:

TreeSet()

Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<?
extends E> c)

Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(Comparator<?
super E> comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(SortedSet<E> s)

Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

這裡排序有兩種實現方法:

1.實現Comparable介面

預設情況下,TreeSet假定插入的元素實現了Comparable介面。這個介面定義了一個方法:

public interface Comparable<T>{

int comparTo(T other);

}

例如String類,如果a與b相等,a.comparTo(b)返回0;如果a>b,返回正值。

但是這種方法有個缺點,就是一個類只能使用一種排序的方法,例如Employee類既想用id進行排序,也想用salary進行排序,腫麼辦?這就要用第二種方法。

2.實現Comparator介面

注意到建構函式TreeSet(Comparator<?
super E> comparator),只要傳遞一個Comparator對象給TreeSet集就可以。

例如:

Set<Employee> otherStaff = new TreeSet<Employee>(new Comparator<Employee>(){public int compare(Employee a, Employee b){return (int)(a.getSalary() - b.getSalary()); //根據salsay的大小排序}});

測試程式

HashSet和TreeSet的測試程式:

這裡重寫了hashCode方法和equals方法。

package com.xujin;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.TreeSet;public class LinkedListTest{public static void main(String...arg){Employee jim = new Employee("Jim", 8000);Employee bob = new Employee("Bob", 9000);Manager jin = new Manager("Gin", 10000, 4000);/*********HashSet類測試************************************/Set<Employee> staff = new HashSet<Employee>();staff.add(jim);staff.add(bob);staff.add(jin);staff.add(bob);//HashCode相同,拒絕添加System.out.println(staff.size());//3Iterator<Employee> iter = staff.iterator();while(iter.hasNext()){Employee e = iter.next();System.out.println(e);}/*********TreeSet類測試************************************/Set<Employee> otherStaff = new TreeSet<Employee>(new Comparator<Employee>(){public int compare(Employee a, Employee b){return (int)(a.getSalary() - b.getSalary()); //根據salsay的大小排序}});otherStaff.add(bob);otherStaff.add(jim);System.out.println(otherStaff);//[id:1 name:Jim salary:8000.0, id:2 name:Bob salary:9000.0]}}class Employee{public Employee(String name){this.name = name;id = nextId;nextId++;}public String toString(){return "id:" + id + " name:" + name +" salary:" + salary;}public int hashCode(){return id;}public boolean equals(Employee e){if(id - e.getId() == 0)return true;return false;}public Employee(String name, double salary){this(name);//調用另一構造器this.salary = salary;}//定義訪問器方法public final String getName(){return name;}public double getSalary(){return salary;}public final int getId(){return id;}//定義更改器方法public final void setName(String name){this.name = name;}public final void setSalary(double salary){this.salary = salary;}public final void raiseSalary(double percent){this.salary *= (1 + percent);}//定義變數private String name = "";//執行個體域初始化private double salary;private int id;private static int nextId = 1;}class Manager extends Employee{public Manager(String name, double salary, double bonus){super(name, salary);//super在構造器中的使用,可以調用超類的構造器setBonus(bonus);}public String toString(){return super.toString() + ",bonus:" + bonus;}public double getBonus(){return bonus;}//重寫getSalary方法public double getSalary(){double baseSalary = super.getSalary();//調用了超類的getSalary方法return baseSalary + bonus;}public void setBonus(double bonus){this.bonus = bonus;}private double bonus;}
使用原則

HashSet和TreeSet

HashSet在速度上略勝一籌,以為她不需要排序。

如果不需要實現排序,就大可不必用TreeSet。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.