[Javase] Collection frame (HashSet)

Source: Internet
Author: User
Tags print object

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)

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.