In-depth research on set in Java

Source: Internet
Author: User
Reprinted: http://www.blog.edu.cn/user1/4859/archives/2005/251431.shtml
In-depth research on set in Java

Author: JJP

Set is the same concept as the set in mathematics, that is, the set without repeating elements.

This article mainly discusses how set implements "No repeated elements" (No duplicate elements) and explains what duplicate is and what is the same address space? Is the return value of equals true? Is the return value of compareto 0? Still have the same hashcode? This article also provides suggestions on how to use the set.

Note: This article does not involve the model.

1. Tree Structure:
Public interface set <E> extends collection <e> {}
Public abstract class implements actset <E> extends actcollection <E> implements set <e> {}
Public class copyonwritearrayset <E> extends abstractset <E> implements serializable {}
Public abstract class enumset <E extends Enum <E> extends actset <E> implements cloneable, serializable {}
Public class hashset <E> extends abstractset <E> implements set <E>, cloneable, serializable {}
Public final class jobstatereasonsextends hashset <jobstatereason> implements printjobattribute {}
Public class implements hashset <E> extends hashset <E> implements set <E>, cloneable, serializable {}
Public class treeset <E> extends abstractset <E> implements sortedset <E>, cloneable, serializable {}
We can see that the instantiated classes are copyonwritearrayset, hashset, linkedhashset, and treeset.
2. How does set implement element uniqueness?
The first section of the Set in javadoc is as follows: "A collection that contains no duplicate elements. More formally, sets contain no pair of elements E1
And E2 such that e1.equals (E2), and at most one null element. As implied by its name, this interface models the mathematical set parameter action ."
This section is correct or wrong. Please refer to the analysis below.
Let's take a look at map first. The elements in map are "key-value" pairs, where "key" must be unique. Treeset and hashset use this feature to implement "No duplicate elements ". It uses the element in the set as the "key" in the map to maintain the uniqueness of the element. How are these keys differentiated in map? Different maps have different approaches and are quite different.
Next we will discuss treeset, hashset, and copyonwritearrayset respectively:
2.1 treeset part:
The following uses treeset as an example for analysis.
See some objects in treeset:
Public class treeset <E> extends abstractset <E>
Implements sortedset <E>, cloneable, java. Io. serializable
{
// The backing Map
Private transient sortedmap <E, Object> m;
// The keyset view of the backing Map
Private transient set <E> keyset;
// DummyValueTo associate with an object in the backing Map
// This is the object of each key.
Private Static final object present = new object ();
// Constructor
Private treeset (sortedmap <E, Object> m ){
This. M = m;
Keyset = M. keyset ();
}
Public treeset (){
This (New treemap <E, Object> ());
}
// The following content is omitted ..........
}
We can see that treeset uses sortedmap as its map to save the "key-value" pair, and the real entity of this sortedmap is treemap.

See example 1:
Import java. util .*;
Public class settest1 {
Public static void main (string [] ARGs ){
Set set = new treeset ();
Set. Add (New setelement1 ("AA "));
Set. Add (New setelement1 ("BB "));
}
Static class setelement1 {
String S;
Public setelement1 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement1) OBJ). S );
}
}
}
This program can be compiled normally, but the exception java. Lang. classcastexception will be thrown during runtime. Why?

See example Program 2:
Import java. util .*;
Public class settest2 {
Public static void main (string [] ARGs ){
Set set = new treeset ();
Set. Add (New setelement2 ("AA "));
Set. Add (New setelement2 ("AA "));
Set. Add (New setelement2 ("BB "));
System. Out. println (SET );
}
Static class setelement2 implements comparable {
String S;
Public setelement2 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public int compareto (Object O ){
Return S. compareto (setelement2) O). S );
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement2) OBJ). S );
}
}
}
Running result:
[AA, BB]
This is exactly what we expected. What is the difference between "Example 1" and "Example 2?
Setelement2 implements the comparable interface, but setelement1 does not. What is the use of setelement2 to implement the comparable interface? Because the "value" of the two elements needs to be compared in the add method of treeset ". See the compare method in treemap:
Private int compare (K K1, K K2 ){
Return (comparator = NULL? (Comparable </*-*/k>) k1). compareto (K2)
: Comparator. Compare (k) k1, (k) K2 ));
}
It can be seen that this method first converts the elements to be compared to the comparable type. Here we can explain why java. Lang. classcastexception is thrown in "Example 1". Because setelement1 does not implement the comparable interface, of course, it cannot be down cast to comparable. As you can see, if you want to use treeset as your set, all the elements in the set must implement the comparable interface.
Here, do you think of using the compareto method in the comparable interface in the treeset to determine whether the elements are the same (duplicate), rather than using other things like equals to determine.

See example 3:
Import java. util. Set;
Import java. util .*;
Public class settest3 {
Public static void main (string [] ARGs ){
Set set = new hashset ();
Set. Add (New setelement3 ("AA "));
Set. Add (New setelement3 ("AA "));
Set. Add (New setelement3 ("BB "));
System. Out. println (SET );
}
Static class setelement3 implements comparable {
String S;
Public setelement3 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public int compareto (Object O ){
// Return S. compareto (setelement3) O). S );
Return-1;
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement3) OBJ). S );
}
}
}
Running result:
[BB, AA, AA]
No. There are two "AA "!! This is because the returned value of compareto is always "-1", that is, "think of any element as different ".

To sum up, are you skeptical about the set function description in javadoc ?!

2.2. hashset part:
The following uses hashset as an example for analysis.
From the main part of the hashset class:
Public class hashset <E> extends abstractset <E>
Implements set <E>, cloneable, java. Io. serializable
{
Static final long serialversionuid =-5024744406713321676l;
Private transient hashmap <E, Object> map;
// Dummy ValueTo associate with an object in the backing Map
// This is the object of each key.
Private Static final object present = new object ();

Public hashset (){
Map = new hashmap <E, Object> ();
}
Public Boolean add (e o ){
Return map. Put (O, present) = NULL;
}
// The following content is omitted ..........
}
 
Public hashset (){
 
Map = new hashmap <E, Object> ();

}
We can see that hashset uses hashmap as its map to save the "key-value" pair.

See example 4:
Import java. util .*;

Public class settest4 {
Public static void main (string [] ARGs ){
Set set = new hashset ();
Set. Add (New setelement4 ("AA "));
Set. Add (New setelement4 ("AA "));
Set. Add (New setelement4 ("BB "));
System. Out. println (SET );
}
Static class setelement4 {
String S;
Public setelement4 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement4) OBJ). S );
}
}
}

Running result:
[BB, AA, AA]
There is no java. Lang. classcastexception in "Example 1", but the running result does not seem to be correct because there are two "AA ".

See example program 5:
Import java. util .*;
Public class settest5 {
Public static void main (string [] ARGs ){
Set set = new hashset ();
Set. Add (New setelement5 ("AA "));
Set. Add (New setelement5 ("AA "));
Set. Add (New setelement5 ("BB "));
System. Out. println (SET );
}
Static class setelement5 {
String S;
Public setelement5 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement5) OBJ). S );
}
Public int hashcode (){
// Return Super. hashcode ();
Return S. hashcode ();
}
}
}
Running result:
[BB, AA]
That's right. What is the difference between "example program 4" and "example program 5? Setelement5 overwrites the hashcode method.

It can be seen that hashset uses the hashcode method to compare elements to determine whether the elements are the same (duplicate), rather than other things like equals.

After talking about this, does the Java class library use equals to determine whether the elements are the same (duplicate) set? See the following.
2.2 copyonwritearrayset:
The copyonwritearrayset class is a class in the Java. util. Concurrent package, so it is thread-safe.
Copyonwritearrayset is a container that uses copyonwritearraylist as its active element. When a new element is added to the copyonwritearraylist, it traverses the entire list and uses equals to compare whether the two elements are the same.

See example program 6:
Import java. util .*;
Import java. util. Concurrent .*;
Public class settest6 {
Public static void main (string [] ARGs ){
Set set = new copyonwritearrayset ();
Set. Add (New setelement6 ("AA "));
Set. Add (New setelement6 ("AA "));
Set. Add (New setelement6 ("BB "));
System. Out. println (SET );
}
Static class setelement6 {
String S;
Public setelement6 (string s ){
This. S = s;
}
Public String tostring (){
Return S;
}
Public Boolean equals (Object OBJ ){
Return S. Equals (setelement6) OBJ). S );
}
}
}
Running result:
[AA, BB]
Okay, everything is done !!

3. Summary:
Some descriptions in javadoc may be inaccurate. Please be careful!

There are many differences in various methods for implementing different elements in set: equals, hashcode, and compareto. However, I have not found a class that uses "determining whether the address space is the same" to determine whether the elements are the same. Of course, we can use three existing methods to "determine whether the address space is the same ".

To sum up, we can summarize three different scenarios of using set: (The following assumes that the element class is element)
A. if you want to use the equals method of element to determine whether the elements are the same, you can use copyonwritearrayset to construct the entity of the class.
B. If the element implements the comparable interface and you want to use the compareto method to determine whether the elements are the same, you can use treeset to construct class entities.
C. If you want to use the method to determine whether the hashcode is the same to determine whether the elements are the same, you can use hashset to construct the entity of the class.

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.