Q. How can we allow duplicate value in set ?
Ans:
In the case of Set the hashcode of the object is used to find the
place/index where the object will be stored.If somehow we can change the
hashcode of the object then the index accessed by using the hashcode
will be changed.So same object will be stored in the Set.
Example:
package com.manish.jlc;
import java.util.HashSet;
import java.util.Set;
public class Test1
{
public static void main(String[] args)
{
Set st=new HashSet();
Student st1=new Student(34);
st.add(st1);
st.add(st1);
st.add(st1);
st.add(st1);
System.out.println(st); // [ 34 ]
st1.age=35;
st.add(st1);
System.out.println(st); //[ 35, 35 ]
}
}
class Student
{
int age;
public Student(int age) {
super();
this.age = age;
}
public int hashCode()
{
return this.age;
}
public String toString()
{
return String.valueOf(age);
}
}
No comments:
Post a Comment