Q:
How can we understand that the elements in the hashset in the Set set are unordered?
Objects in the Set set are not sorted in a specific order, and the objects are not repeated. A set implementation class: hashset uses the hash algorithm to access objects in the set. hash is: object Value --> hash code --> element location. so I have a question: "the objects in the Set set are not sorted in specific order" and "the correspondence between the object values in the hashset and the element location" is a bit contradictory? Or a bit awkward. This should be an understanding question. Please correct my remarks and help answer my questions?
Thank you!
A:
To understand this problem, we should consider that set is an interface. The interface contract is simple and will not be guaranteed too much. The focus of the set contract is "the set of elements that do not repeat", and there is no guarantee for the order (that is, there is no restriction, and the order is disordered ). Classes that implement this interface can provide both ordered implementation and unordered implementation.
When storing data, hashset obviously needs to be placed in the array behind it in a certain order, but the order is not user controllable, and it is "unordered" for users ".
In contrast, the contract of the sortedset Interface contains the meaning of "a set of elements that are not repeated and sorted in the way specified by the user. The sortedset interface meets the contract of the Set interface, and an additional "ordered" contract is added. Treeset implements the sortedset (and set) interface, and it is ordered.
Hashmap map = new hashmap ();
// Storage value
Hashset HS = new hashset ();
For (INT I = 0; I <dsjlist. Size (); I ++ ){
Dsj = (dsj) dsjlist. Get (I );
String year = dsj. getshijian (). tostring (). substring (0, 4 );
HS. Add (year );
}
// Value
Iterator it = HS. iterator ();
While (it. hasnext ()){
Map = new hashmap ();
Nrlist = new arraylist ();
String year = (string) it. Next ();
Map. Put ("year", year );
Nrlist = dsjmanager. getdsjlist ("where Shijian like '" + year + "% '");
Map. Put ("nrlist", nrlist );
Yearlist. Add (MAP );
}
Note:
If sorted is used, it is stored in order!
The natural order is the order in which things develop freely, not the human order.
Private void dosort (){
Hashset <integer> Va = new hashset <integer> ();
Va. Add (2007111315 );
Va. Add (2007111314 );
Va. Add (2007111318 );
Va. Add (2007111313 );
Treeset Ts = new treeset (VA );
TS. comparator ();
System. Out. println (TS );
}