HashSet (need to rewrite hashcode and Equals method) __ Basic knowledge

Source: Internet
Author: User

Things that are generally described need to be added to the collection, both methods need to be rewritten

Delete and determine whether the existence of elements, are first judged hashcode to see if there is, if there is continued equals ();


Import java.util.*;
	Class Person {private String name;
	private int age;
		Person (String Name,int age) {this.name=name;
	This.age=age;
	The public int hashcode ()//Overrides {return Name.hashcode () +age; The public boolean equals (object obj)//rewrite Object cannot be swapped for {if (!
		  obj instanceof person), return false;

		  Person p= (person) obj;

		  System.out.println (this.name+ "..." +p.name);
	Return This.name.equals (p.name) &&this.age==p.age;
	Public String GetName () {return name;
	public int getage () {return age;

		} class Hashsetdemo {public static void main (string[] args) {hashset hs=new hashset ();
		Hs.add (New person ("lisi01", 30));
		Hs.add (New person ("lisi02", 33));
		Hs.add (New person ("lisi03", 35));
		Hs.add (New person ("lisi02", 33));
		Hs.add (New person ("lisi01", 30));
		Hs.add (New person ("lisi04", 32));

		Hs.add (New person ("lisi03", 35));

		Iterator It=hs.iterator ();
		   while (It.hasnext ()) {person p= (person) it.next ();; SOP (P.GetName () + "" +p.getage ());

	The public static void sop (Object obj) {System.out.println (obj);
 }
}


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.