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