Set: Elements are unordered, non-repeatable
Haseset: The underlying data structure is a hash table
Define a class of Demo
Get The demo object,System.out.println (demo), print the demo object,[email Protected]
The Demo object is stored in memory in the hash table, and it is sorted by hash value, so it is unordered
ImportJava.util.HashSet;classdemo{} Public classHashsetdemo {/** * @paramargs*/ Public Static voidMain (string[] args) {Demo demo1=NewDemo (); Demo Demo2=NewDemo (); System.out.println (DEMO1); System.out.println (DEMO2); HashSet Set=NewHashSet (); Set.add (DEMO1); Set.add (DEMO2); SYSTEM.OUT.PRINTLN (set); }}
Results:
[Email protected]
[Email protected]
[[Email protected], [email protected]]
Define a class of Demo
Override the hashcode () method to return a fixed number, for example: $, Print object display,[email protected]
Get multiple objects, hash values are the same, at this point in haseset , using the equals () method, determine whether the same object, if not the same object, will be deferred storage
ImportJava.util.HashSet;classdemo{@Override Public inthashcode () {return90; } @Override Public Booleanequals (Object obj) {System.out.println ("Call here to determine if the same object"); return Super. Equals (obj); }} Public classHashsetdemo {/** * @paramargs*/ Public Static voidMain (string[] args) {Demo demo1=NewDemo (); Demo Demo2=NewDemo (); System.out.println (DEMO1); System.out.println (DEMO2); HashSet Set=NewHashSet (); Set.add (DEMO1); Set.add (DEMO2); SYSTEM.OUT.PRINTLN (set); }}
Results:
[Email protected]
[Email protected]
Called here to determine whether the same object
[[Email protected], [email protected]]
[Javase] Collection frame (HashSet)