📜  用Java设置

📅  最后修改于: 2022-05-13 01:54:46.375000             🧑  作者: Mango

用Java设置

set 接口存在于Java.util 包中,并扩展了 Collection 接口,它是一个无序的对象集合,其中不能存储重复值。它是一个实现数学集的接口。该接口包含从 Collection 接口继承的方法,并添加了限制重复元素插入的功能。有两个扩展集合实现的接口,即 SortedSet 和 NavigableSet。

在上图中,navigable set 扩展了 sorted set 接口。由于集合不保留插入顺序,因此可导航集合接口提供了在集合中导航的实现。实现可导航集的类是 TreeSet,它是自平衡树的实现。因此,这个界面为我们提供了一种在这棵树中导航的方式。

声明: Set 接口声明为:

public interface Set extends Collection 

创建集合对象

由于 Set 是一个接口,因此无法创建排版的对象。我们总是需要一个扩展这个列表的类来创建一个对象。而且,在Java 1.5 中引入泛型之后,可以限制可以存储在 Set 中的对象类型。这个类型安全的集合可以定义为:

// Obj is the type of the object to be stored in Set 
Set set = new HashSet (); 

让我们以下面的表格格式讨论下面提供的 Set 接口中的方法,如下所示:

MethodDescription
add(element)This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
addAll(collection)This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
clear()This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists.
contains(element)This method is used to check whether a specific element is present in the Set or not.
containsAll(collection)This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing.
hashCode()This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance of the Set.
isEmpty()This method is used to check whether the set is empty or not.
iterator()This method is used to return the iterator of the set. The elements from the set are returned in a random order.
remove(element)This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False.
removeAll(collection)This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.
retainAll(collection)This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call.
size()This method is used to get the size of the set. This returns an integer value which signifies the number of elements.
toArray()This method is used to form an array of the same elements as that of the Set.

插图:说明集界面的示例程序

Java
// Java program Illustrating Set Interface
 
// Importing utility classes
import java.util.*;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Demonstrating Set using HashSet
        // Declaring object of type String
        Set hash_Set = new HashSet();
 
        // Adding elements to the Set
        // using add() method
        hash_Set.add("Geeks");
        hash_Set.add("For");
        hash_Set.add("Geeks");
        hash_Set.add("Example");
        hash_Set.add("Set");
 
        // Printing elements of HashSet object
        System.out.println(hash_Set);
    }
}


Java
// Java Program Demonstrating Operations on the Set
// such as Union, Intersection and Difference operations
 
// Importing all utility classes
import java.util.*;
 
// Main class
public class SetExample {
   
    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of Set class
        // Declaring object of Integer type
        Set a = new HashSet();
       
        // Adding all elements to List
        a.addAll(Arrays.asList(
            new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
       
      // Again declaring object of Set class
      // with reference to HashSet
        Set b = new HashSet();
         
      b.addAll(Arrays.asList(
            new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
 
         
        // To find union
        Set union = new HashSet(a);
        union.addAll(b);
        System.out.print("Union of the two Set");
        System.out.println(union);
 
        // To find intersection
        Set intersection = new HashSet(a);
        intersection.retainAll(b);
        System.out.print("Intersection of the two Set");
        System.out.println(intersection);
 
        // To find the symmetric difference
        Set difference = new HashSet(a);
        difference.removeAll(b);
        System.out.print("Difference of the two Set");
        System.out.println(difference);
    }
}


Java
// Java Program Demonstrating Working of Set by
// Adding elements using add() method
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Set and
        // declaring object of type String
        Set hs = new HashSet();
 
        // Adding elements to above object
        // using add() method
        hs.add("B");
        hs.add("B");
        hs.add("C");
        hs.add("A");
 
        // Printing the elements inside the Set object
        System.out.println(hs);
    }
}


Java
// Java code to demonstrate Working of Set by
// Accessing the Elements og the Set object
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Set and
        // declaring object of type String
        Set hs = new HashSet();
 
        // Elements are added using add() method
        // Later onwards we wil show accessing the same
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("A");
 
        // Print the Set object elements
        System.out.println("Set is " + hs);
 
        // Declaring a string
        String check = "D";
 
        // Check if the above string exists in
        // the SortedSet or not
        // using contains() method
        System.out.println("Contains " + check + " "
                           + hs.contains(check));
    }
}


Java
// Java Program Demonstrating Working of Set by
// Removing Element/s from the Set
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring object of Set of type String
        Set hs = new HashSet();
 
        // Elements are added
        // using add() method
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("B");
        hs.add("D");
        hs.add("E");
 
        // Printing initial Set elements
        System.out.println("Initial HashSet " + hs);
 
        // Removing custom element
        // using remove() method
        hs.remove("B");
 
        // Printing Set elements after removing an element
        // and printing updated Set elements
        System.out.println("After removing element " + hs);
    }
}


Java
// Java Program to Demonstrate Working of Set by
// Iterating through the Elements
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of Set and declaring String type
        Set hs = new HashSet();
 
        // Adding elements to Set 
        // using add() method
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("B");
        hs.add("D");
        hs.add("E");
 
        // Iterating through the Set
        // via for-each loop
        for (String value : hs)
 
            // Printing all the values inside the object
            System.out.print(value + ", ");
         
        System.out.println();
    }
}


Java
// Java program Demonstrating Creation of Set object
// Using the Hashset class
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of Set of type String
        Set h = new HashSet();
 
        // Adding elements into the HashSet
        // using add() method
 
        // Custom input elements
        h.add("India");
        h.add("Australia");
        h.add("South Africa");
 
        // Adding the duplicate element
        h.add("India");
 
        // Displaying the HashSet
        System.out.println(h);
 
        // Removing items from HashSet
        // using remove() method
        h.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + h);
 
        // Iterating over hash set items
        System.out.println("Iterating over set:");
 
        // Iterating through iterators
        Iterator i = h.iterator();
 
        // It holds true till there is a single element
        // remaining in the object
        while (i.hasNext())
 
            System.out.println(i.next());
    }
}


Java
// Java program to demonstrate the
// creation of the set object
// using the EnumSet class
import java.util.*;
 
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }
;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // Creating a set
        Set set1;
 
        // Adding the elements
        set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
                          Gfg.LEARN, Gfg.CODE);
 
        System.out.println("Set 1: " + set1);
    }
}


Java
// Java program to demonstrate the
// creation of Set object using
// the LinkedHashset class
import java.util.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        Set lh = new LinkedHashSet();
 
        // Adding elements into the LinkedHashSet
        // using add()
        lh.add("India");
        lh.add("Australia");
        lh.add("South Africa");
 
        // Adding the duplicate
        // element
        lh.add("India");
 
        // Displaying the LinkedHashSet
        System.out.println(lh);
 
        // Removing items from LinkedHashSet
        // using remove()
        lh.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + lh);
 
        // Iterating over linked hash set items
        System.out.println("Iterating over set:");
        Iterator i = lh.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}


Java
// Java Program Demonstrating Creation of Set object
// Using the TreeSet class
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a Set object and declaring it of String
        // type
        // with reference to TreeSet
        Set ts = new TreeSet();
 
        // Adding elements into the TreeSet
        // using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");
 
        // Adding the duplicate
        // element
        ts.add("India");
 
        // Displaying the TreeSet
        System.out.println(ts);
 
        // Removing items from TreeSet
        // using remove()
        ts.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + ts);
 
        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator i = ts.iterator();
 
        while (i.hasNext())
            System.out.println(i.next());
    }
}


输出
[Set, Example, Geeks, For]

设置界面上的操作

集合界面允许用户对集合执行基本的数学运算。让我们以两个数组来理解这些基本操作。令 set1 = [1, 3, 2, 4, 8, 9, 0] 和 set2 = [1, 3, 7, 5, 4, 0, 7, 5]。那么对集合可能的操作是:

1. 交集:此操作从给定的两个集合中返回所有公共元素。对于上述两组,交集将是:

Intersection = [0, 1, 3, 4] 

2.并集:此操作将一组中的所有元素与另一组相加。对于上述两组,联合将是:

Union = [0, 1, 2, 3, 4, 5, 7, 8, 9] 

3.差异:此操作从另一组中删除一组中存在的所有值。对于上述两组,不同之处在于:

Difference = [2, 8, 9]

现在让我们实现上面定义的以下操作,如下所示:

例子:

Java

// Java Program Demonstrating Operations on the Set
// such as Union, Intersection and Difference operations
 
// Importing all utility classes
import java.util.*;
 
// Main class
public class SetExample {
   
    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of Set class
        // Declaring object of Integer type
        Set a = new HashSet();
       
        // Adding all elements to List
        a.addAll(Arrays.asList(
            new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
       
      // Again declaring object of Set class
      // with reference to HashSet
        Set b = new HashSet();
         
      b.addAll(Arrays.asList(
            new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
 
         
        // To find union
        Set union = new HashSet(a);
        union.addAll(b);
        System.out.print("Union of the two Set");
        System.out.println(union);
 
        // To find intersection
        Set intersection = new HashSet(a);
        intersection.retainAll(b);
        System.out.print("Intersection of the two Set");
        System.out.println(intersection);
 
        // To find the symmetric difference
        Set difference = new HashSet(a);
        difference.removeAll(b);
        System.out.print("Difference of the two Set");
        System.out.println(difference);
    }
}
输出
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection of the two Set[0, 1, 3, 4]
Difference of the two Set[2, 8, 9]

对 SortedSet 执行各种操作

Java 1.5 引入泛型后,可以限制Set 中可以存储的对象类型。由于 Set 是一个接口,它只能与实现该接口的类一起使用。 HashSet 是广泛使用的实现 Set 接口的类之一。现在,让我们看看如何对 HashSet 执行一些常用的操作。我们将执行以下操作,如下所示:

  1. 添加元素
  2. 访问元素
  3. 移除元素
  4. 迭代元素
  5. 遍历 Set

现在让我们分别讨论这些操作,如下所示:

操作 1:添加元素

为了向 Set 添加元素,我们可以使用 add() 方法。但是,插入顺序不会保留在 Set 中。在内部,对于每个元素,都会生成一个散列,并根据生成的散列存储值。这些值按升序进行比较和排序。我们需要注意,不允许重复元素,所有重复元素都将被忽略。而且,Set 接受 Null 值。

例子

Java

// Java Program Demonstrating Working of Set by
// Adding elements using add() method
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Set and
        // declaring object of type String
        Set hs = new HashSet();
 
        // Adding elements to above object
        // using add() method
        hs.add("B");
        hs.add("B");
        hs.add("C");
        hs.add("A");
 
        // Printing the elements inside the Set object
        System.out.println(hs);
    }
}
输出
[A, B, C]

操作 2:访问元素

添加元素后,如果我们希望访问元素,可以使用内置方法,如 contains()。

例子

Java

// Java code to demonstrate Working of Set by
// Accessing the Elements og the Set object
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Set and
        // declaring object of type String
        Set hs = new HashSet();
 
        // Elements are added using add() method
        // Later onwards we wil show accessing the same
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("A");
 
        // Print the Set object elements
        System.out.println("Set is " + hs);
 
        // Declaring a string
        String check = "D";
 
        // Check if the above string exists in
        // the SortedSet or not
        // using contains() method
        System.out.println("Contains " + check + " "
                           + hs.contains(check));
    }
}
输出
Set is [A, B, C]
Contains D false

操作 3:删除值

可以使用 remove() 方法从 Set 中删除这些值。

例子

Java

// Java Program Demonstrating Working of Set by
// Removing Element/s from the Set
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring object of Set of type String
        Set hs = new HashSet();
 
        // Elements are added
        // using add() method
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("B");
        hs.add("D");
        hs.add("E");
 
        // Printing initial Set elements
        System.out.println("Initial HashSet " + hs);
 
        // Removing custom element
        // using remove() method
        hs.remove("B");
 
        // Printing Set elements after removing an element
        // and printing updated Set elements
        System.out.println("After removing element " + hs);
    }
}
输出
Initial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]

操作 4:遍历集合

有多种方法可以遍历 Set。最著名的一种是使用增强的 for 循环。

例子

Java

// Java Program to Demonstrate Working of Set by
// Iterating through the Elements
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of Set and declaring String type
        Set hs = new HashSet();
 
        // Adding elements to Set 
        // using add() method
 
        // Custom input elements
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("B");
        hs.add("D");
        hs.add("E");
 
        // Iterating through the Set
        // via for-each loop
        for (String value : hs)
 
            // Printing all the values inside the object
            System.out.print(value + ", ");
         
        System.out.println();
    }
}
输出
A, B, C, D, E, 

第 1 类:哈希集 

在集合框架中实现的 HashSet 类是哈希表数据结构的固有实现。我们插入到 HashSet 中的对象不保证以相同的顺序插入。对象是根据它们的哈希码插入的。此类还允许插入 NULL 元素。让我们看看如何使用这个类创建一个集合对象。

例子

Java

// Java program Demonstrating Creation of Set object
// Using the Hashset class
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of Set of type String
        Set h = new HashSet();
 
        // Adding elements into the HashSet
        // using add() method
 
        // Custom input elements
        h.add("India");
        h.add("Australia");
        h.add("South Africa");
 
        // Adding the duplicate element
        h.add("India");
 
        // Displaying the HashSet
        System.out.println(h);
 
        // Removing items from HashSet
        // using remove() method
        h.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + h);
 
        // Iterating over hash set items
        System.out.println("Iterating over set:");
 
        // Iterating through iterators
        Iterator i = h.iterator();
 
        // It holds true till there is a single element
        // remaining in the object
        while (i.hasNext())
 
            System.out.println(i.next());
    }
}
输出
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India

第 2 类:枚举集

在集合框架中实现的 EnumSet 类是用于枚举类型的 Set 接口的专门实现之一。它是一个高性能的集合实现,比 HashSet 快得多。枚举集中的所有元素都必须来自一个枚举类型,该枚举类型是在显式或隐式创建集合时指定的。让我们看看如何使用这个类创建一个集合对象。

例子

Java

// Java program to demonstrate the
// creation of the set object
// using the EnumSet class
import java.util.*;
 
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }
;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // Creating a set
        Set set1;
 
        // Adding the elements
        set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
                          Gfg.LEARN, Gfg.CODE);
 
        System.out.println("Set 1: " + set1);
    }
}
输出
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]

第三类: LinkedHashSet

在集合框架中实现的 LinkedHashSet 类是 HashSet 的有序版本,它维护一个跨所有元素的双向链表。当需要维护迭代顺序时,使用此类。当遍历 HashSet 时,顺序是不可预测的,而 LinkedHashSet 让我们按照元素插入的顺序遍历元素。让我们看看如何使用这个类创建一个集合对象。

例子

Java

// Java program to demonstrate the
// creation of Set object using
// the LinkedHashset class
import java.util.*;
 
class GFG {
 
    public static void main(String[] args)
    {
        Set lh = new LinkedHashSet();
 
        // Adding elements into the LinkedHashSet
        // using add()
        lh.add("India");
        lh.add("Australia");
        lh.add("South Africa");
 
        // Adding the duplicate
        // element
        lh.add("India");
 
        // Displaying the LinkedHashSet
        System.out.println(lh);
 
        // Removing items from LinkedHashSet
        // using remove()
        lh.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + lh);
 
        // Iterating over linked hash set items
        System.out.println("Iterating over set:");
        Iterator i = lh.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}
输出
[India, Australia, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

第 4 类:树集

在集合框架中实现的 TreeSet 类和 SortedSet 接口和 SortedSet 的实现扩展了 Set 接口。它的行为类似于一个简单的集合,不同之处在于它以排序格式存储元素。 TreeSet 使用树数据结构进行存储。对象按排序的升序存储。但是我们可以使用 TreeSet.descendingIterator() 方法以降序迭代。让我们看看如何使用这个类创建一个集合对象。

例子

Java

// Java Program Demonstrating Creation of Set object
// Using the TreeSet class
 
// Importing utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a Set object and declaring it of String
        // type
        // with reference to TreeSet
        Set ts = new TreeSet();
 
        // Adding elements into the TreeSet
        // using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");
 
        // Adding the duplicate
        // element
        ts.add("India");
 
        // Displaying the TreeSet
        System.out.println(ts);
 
        // Removing items from TreeSet
        // using remove()
        ts.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + ts);
 
        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator i = ts.iterator();
 
        while (i.hasNext())
            System.out.println(i.next());
    }
}
输出
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa