Friday 7 September 2018

                                                    what is the o/p of this program?

package govind;

import java.util.HashSet;

public class NamePrint {

private String name;

public NamePrint(String name) {
super();
this.name = name;
}

@Override
public String toString() {
return name;
}


public static void main(String[] args) {

HashSet h1=new HashSet<>();
String s1=new String("JavaTechnology");
String s2=new String("JavaTechnology");
NamePrint np1=new NamePrint("GovindBallabhKhan");
NamePrint np2=new NamePrint("GovindBallabhKhan");

h1.add(s1);
h1.add(s2);
h1.add(np1);
h1.add(np2);
System.out.println(h1);


}



}

o/p---------------------
[GovindBallabhKhan, GovindBallabhKhan, JavaTechnology]

As String class overrides hashcode and equals method, it won’t allow same string twice in HashSet,
but we did not implement hashcode and equals method for NamePrint class, so each object will have different hashcode hence can be inserted
 in HashSet.


No comments:

Post a Comment