Java programming language Set collection method demo

Source: Internet
Author: User



Java programming language Set collection method demo


Import Java.util.collection;import java.util.comparator;import Java.util.hashset;import Java.util.Iterator;import Java.util.set;public class Hashsetdemos {public static void main (string[] args) {//new set of Set class Set St = new HashSet (); St . Add ("ABC1"); St.add ("ABC2"); St.add ("ABC1"); St.add ("ABC2");//Output only ABC1 and ABC2 do not allow elements to repeat iterator it = st.iterator (); while (It.hasnext ()) {System.out.println (It.next ());} St.removeall (ST), St.add (New Studenti ("Lisi"), St.add (New Studenti ("Lisi"), St.add (New Studenti ("Lisan", 22)) St.add (New Studenti ("Lisan")), Iterator its = St.iterator (); while (Its.hasnext ()) {Studenti s = (studenti) its.next () ; System.out.println (S.getname () + "" +s.getage ());}} Class studenti{private String name;private int age; Studenti (String name, int age) {this.name=name;this.age = age;} public int getage () {return age;} Public String GetName () {return name;} Public String toString () {return ' The student Name: +name ' + ' and ' age ': ' + age;} public int hashcode () {return Name.hashcode () +age*10;} public boolean equals (object obj) {if (this = = obj) return true;//The same object is placed two times, directly returning True if (! (       obj instanceof Studenti)) throw new ClassCastException ("type error");       Studenti p = (studenti) obj; return this. Name.equals (p.name) && this.age = = P.age;}}


To run the program:















Java programming language Set collection method demo

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.