Java Collection class learning (4) -- Set

Source: Internet
Author: User
Tags addall comparable
Document directory
  • 1.5.1 Overview
  • 1.5.2 common methods
1.5 set1.5.1 Overview

The concept of set in Java is the same as that in mathematics. The biggest feature of set is that it does not allow repeated elements to be stored in it. Based on this feature, we can use the set interface to meet the storage requirements of the product categories mentioned above. Set can be used to filter elements stored in other sets to obtain a new set that does not contain duplicates.

1.5.2 common methods

According to the definition, the set interface inherits the collection interface and does not allow repeated items in the set. All original methods are ready-made and no new methods are introduced. The specific set implementation class depends on the equals () method of the added object to check equality.

Let's briefly describe the functions of each method:

U public int size (): return the number of elements in the set. If the number of elements contained in the set is greater than integer. max_value, return integer. max_value.

U public Boolean isempty (): returns true if the set contains no elements.

U public Boolean contains (Object O): returns true if set contains the specified element.

U public iterator ()

L return the iterator of elements in the set.

L element return has no specific order, unless set is an instance that improves the guarantee of some classes

U public object [] toarray (): returns an array containing all elements in the set.

U public object [] toarray (object [] A): returns an array containing all elements in the set. The runtime type of the returned array is the runtime type of the specified array.

U public Boolean add (Object O): If the specified element does not exist in the Set, add it to the set.

U public Boolean remove (Object O): If a specified element exists in the set, it is deleted from the set.

U public Boolean removeall (collection C): If the set contains the specified set, all elements of the specified set are deleted from the set.

U public Boolean containsall (collection C): returns true if set contains all elements of the specified set. If the specified set is also a set, the method returns true only when it is a subset of the current set.

U public Boolean addall (collection C): If there is no element in the specified set, add all elements to the set.

U public Boolean retainall (collection C): retains only the elements of the specified set contained in the Set (optional ). In other words, all elements not included in the specified set are deleted from the set. If the specified set is also a set, the effect of modifying the set operation is to set its value to the intersection of two sets.

U public Boolean removeall (collection C): If the set contains the specified set, all elements of the specified set are deleted from the set.

U public void clear (): deletes all elements from the set.

The set framework supports two common implementations: hashset, treeset, and javashashset. The following table describes the Common Implementation classes of set:

 

 

Brief Introduction

Implementation

Operation Features

Member requirements

Set

Duplicate members are not allowed.

Hashset

Attackers can traverse members unordered.

A member can be an object of any object subclass. If the equals method is overwritten, modify the hashcode method.

Treeset

Traverse members in an external order;

Added sortedset and supported operations that require sequence, such as subsets.

The member must implement the comparable interface, or use comparator to construct a treeset. The members are generally of the same type.

Linkedhashset

The members are traversed by the insertion order of the members.

Similar to hashset members

 

In more cases, you will use hashset to store repeated free sets. In addition, hashset uses the hash algorithm to access object elements. Therefore, the corresponding class of the object added to the hashset needs to be implemented in an appropriate way to implement the hashcode () method. Although most system classes cover the default hashcode () implementation in the object, do not forget to overwrite the hashcode () when creating your own class to be added to the hashset ().

For the use of set, we will first describe it with a simple example:

Import java. util .*;

Public class hashsetdemo {

Public static void main (string [] ARGs ){

Set set1 = new hashset ();

If (set1.add ("A") {// added successfully

System. Out. println ("1 add true ");

}

If (set1.add ("A") {// failed to add

System. Out. println ("2 add true ");

}

Set1.add ("000"); // Add the object to the Set set

Set1.add ("111 ");

Set1.add ("222 ");

System. Out. println ("set1 set size:" + set1.size ());

System. Out. println ("set1 set content:" + set1 );

Set1.remove ("000"); // remove the "000" object from set1 of the Set

System. Out. println ("the content after the set set1 removes 000:" + set1 );

System. Out. println ("whether set1 in the set contains 000:" + set1.contains ("000 "));

System. Out. println ("whether set1 in the set contains 111:" + set1.contains ("111 "));

Set set2 = new hashset ();

Set2.add ("111 ");

Set2.addall (set1); // Add all the elements in the set1 set to set2.

System. Out. println ("set2 set content:" + set2 );

Set2.clear (); // clear the elements in set1 of the set.

System. Out. println ("set set2 is empty:" + set2.isempty ());

Iterator = set1.iterator (); // get an iterator

While (iterator. hasnext () {// traverse

OBJECT element = iterator. Next ();

System. Out. println ("iterator =" + element );

}

// Convert the set1 set to an array

Object s [] = set1.toarray ();

For (INT I = 0; I <S. length; I ++ ){

System. Out. println (s [I]);

}

}

}

The execution result of the program is:

1 add true

Size of set1 in a set: 4

Set set1 content: [222, A, 000,111]

The content after the set set1 is removed 222: [111, A,]

Whether the set set1 contains 000: false

Whether the set set1 contains 111: True

Set set2 content: [222, A, 111]

Whether the set2 set is null: True

Iterator = 222

Iterator =

Iterator = 111

222

A

111

From the above simple example, we can find that the methods in set are the same as those in the collection directly. The only thing to note is that the elements stored in the set cannot be repeated.

Let's look at another example to learn about the features of other set implementation classes:

Package c08;

Import java. util .*;

Public class setsortexample {

Public static void main (string ARGs []) {

Set set1 = new hashset ();

Set set2 = new linkedhashset ();

For (INT I = 0; I <5; I ++ ){

// Generate a random number and put it into the set

Int S = (INT) (math. rank () * 100 );

Set1.add (New INTEGER (s ));

Set2.add (New INTEGER (s ));

System. Out. println ("the" + I + "Random Number Generation:" + S );

}

System. Out. println ("pre-sorted hashset:" + set1 );

System. Out. println ("sorted hashset:" + set2 );

// Use treeset to refactor and sort another set

Set sortedset = new treeset (set1 );

System. Out. println ("sorted treeset:" + sortedset );

}

}

The execution result of this program is:

0th Random Number Generation: 96

1st Random Number Generation: 64

2nd Random Number Generation: 14

3rd Random Number Generation: 95

4th Random Number Generation: 57

Pre-sorted hashset: [64, 96, 95, 57, 14]

Sorted prior to hashset: [96, 64, 14, 95, 57]

Sorted treeset: [14, 57, 64, 95, 96]

In this example, we can know that the order in which hashset elements are stored has nothing to do with the order in which they are added, while that in which hashset elements are added. Treeset sorts and stores the elements in our set.

In general, the treeset implementation is useful when you want to extract elements in an ordered manner from a set. In order to proceed smoothly, the elements added to the treeset must be sorted. You also need to support the comparable interface for class objects added to the treeset. The implementation of the comparable interface has been briefly introduced in the map in the previous section. For the moment, assume that a tree knows how to keep the elements of the Java. Lang Wrapper class in order. Generally, it is faster to add elements to a hashset and then convert the set to a treeset for sequential traversal. This is very similar to the use of hashmap.

In fact, the implementation principle of set is based on map. Through the further analysis of the set, we can better understand this point.

1.5.3 implementation principle

The concept of set in Java is the same as that in mathematics. Both indicate that elements in a set cannot be duplicated.

We will find that many implementation classes in set are very similar to those in map. In addition, when we talk about map, we also mentioned that "key-value pairs" in map cannot be repeated. The elements in the set cannot be the same. Taking hashset as an example, we will find that set uses the unique feature of "key" in map.

First, let's take a look at the attributes in hashset:

Let's look at it with the constructor:

Through these methods, we can find that all the operations of hashset are implemented based on hashmap. Let's take a look at how hashmap can be used to ensure that the elements of our hashset are not repetitive:

When we see this operation, we can find that the clever Implementation of hashset is: to create a "key-Value Pair", "key" is the object we want to store, and "value" is a constant. This ensures that the information we need to store is the "key ". The "key" cannot be repeated in map, which ensures that all elements stored in the set are not repeated. To determine whether the element is successfully added, it is to determine whether the "key-Value Pair" stored in the map already exists. If so, the return value must be a constant: present, indicates that the addition failed. If it does not exist, null indicates that the value is successfully added.

Let's look at the implementation of other methods:

After learning about this, it is not difficult to understand why attention should be paid to hashmap in the same way as hashset. The implementation classes of other sets are similar.

So far we should be able to better understand the set.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.