Reputation: 27640
Is it possible to allow duplicate values in the Set collection?
Is there any way to make the elements unique and have some copies of them? Is there any functions for Set collection for having duplicate values in it?
Upvotes: 15
Views: 81642
Reputation: 31
You can use Tree Map instead :
Key can be used as element you wish to store and Value will be the frequency of input element.
The insertion and removal will require custom handling.
More details can be found in the java docs of tree map
Overall time complexity will remain same as TreeSet O(log N) but worse than a HashSet O(1)
firstEntry() -> provides smallest element entry, Time Complexity : O(Log N)
lastEntry() -> provides greatest element entry, Time Complexity : O(Log N)
Upvotes: 0
Reputation: 1
Set will store unique values and if you wants to store duplicate values then for list,but still if you want duplicate values in set then create set of ArrayList so that you can put duplicate elements into it.
Set<ArrayList> s = new HashSet<ArrayList>();
ArrayList<String> arr = new ArrayList<String>();
arr.add("First");
arr.add("Second");
arr.add("Third");
arr.add("Fourth");
arr.add("First");
s.add(arr);
Upvotes: 0
Reputation: 1
Well, In this case we are trying to break the purpose of specific collection. If we want to allow duplicate records simply use list or multimap.
Upvotes: 0
Reputation: 70909
These sound like interview questions, so I'll answer them like interview questions...
Is it possible to allow duplicate values in the Set collection?
Yes, but it requires that the person implementing the Set
violate the design contract upon which Set
is built. Basically, I could write a class that extends Set
and doesn't enforce Set
's promises.
In addition, other violations are possible. I could use a Set
implementation that relies upon Java's hashCode()
contract. Then if I provided an Object
that violates Java's hashcode contract, I might be able to place two objects into the set which are equal, but yeild different hashcodes (because they might not be checked in equality against each other due to being in different hash bucket chains.
Is there any way to make the elements unique and have some copies of them?
It basically depends on how you define uniqueness. If an object's uniqueness is determined by its value, then one can have multiple copies of the same unique object; however, if the object's uniqueness is determined by its instance, then by definition it would not be possible to have multiple copies of the same object. You could however have multiple references to them.
Is there any functions for Set collection for having duplicate values in it?
The Set
interface doesn't have any functions for detecting / reporting duplicates; however, it is based on the Collections interface, which has to support the List interface, so it is possible to pass duplicates into a Set; however, a properly implemented Set
will just ignore the duplicates, and present one copy of every element determined to be unique.
Upvotes: 1
Reputation: 3549
Sun's view on "bags" (AKA multisets):
We are extremely sympathetic to the desire for type-safe collections. Rather than adding a "band-aid" to the framework that enforces type-safety in an ad hoc fashion, the framework has been designed to mesh with all of the parameterized-types proposals currently being discussed. In the event that parameterized types are added to the language, the entire collections framework will support compile-time type-safe usage, with no need for explicit casts. Unfortunately, this won't happen in the the 1.2 release. In the meantime, people who desire runtime type safety can implement their own gating functions in "wrapper" collections surrounding JDK collections.
(source; note it is old and possibly obsolete -ed.)
Apart from Google's collections API, you can use Apache Commons Collections.
Apache Commons Collections:
http://commons.apache.org/collections/
Upvotes: 2
Reputation: 20946
Ever considered using a java.util.List instead?
Otherwise I would recommend a Multiset from Google Guava (the successor to Google Collections, which this answer originally recommended -ed.).
Upvotes: 29
Reputation: 1
public class SET {
public static void main(String[] args) {
Set set=new HashSet();
set.add(new AB(10, "pawan@email"));
set.add(new AB(10, "pawan@email"));
set.add(new AB(10, "pawan@email"));
Iterator it=set.iterator();
while(it.hasNext()){
Object o=it.next();
System.out.println(o);
}
}
}
public class AB{
int id;
String email;
public AB() {
System.out.println("DC");
}
AB(int id,String email){
this.id=id;
this.email=email;
}
@Override public String toString() {
// TODO Auto-generated method stub return ""+id+"\t"+email;}
}
}
Upvotes: -1
Reputation: 560
You can do so by overriding hashcode as given below:
public class Test
{
static int a=0;
@Override
public int hashCode()
{
a++;
return a;
}
public static void main(String[] args)
{
Set<Test> s=new HashSet<Test>();
Test t1=new Test();
Test t2=t1;
s.add(t1);
s.add(t2);
System.out.println(s);
System.out.println("--Done--");
}
}
Upvotes: 0
Reputation: 1
This question was asked to me also in an interview. I think the answer is, ofcourse Set will not allow duplicate elements and instead ArrayList or other collections should be used for the same, however overriding equals() for the type of the object being stored in the set will allow you to manipulate on the comparison logic. And hence you may be able to store duplicate elements in the Set. Its more of a hack, which would allow non-unique elements in the Set and ofcourse is not recommended in production level code.
Upvotes: 0
Reputation: 174
As mentioned choose the right collection for the task and likely a List will be what you need. Messing with the equals(), hashcode() or compareTo() to break identity is generally a bad idea simply to wedge an instance into the wrong collection to start with. Worse yet it may break code in other areas of the application that depend on these methods producing valid comparison results and be very difficult to debug or track down such errors.
Upvotes: 0
Reputation: 31064
The very definition of a Set disallows duplicates. I think perhaps you want to use another data structure, like a List, which will allow dups.
Is there any way to make the elements unique and have some copies of them?
If for some reason you really do need to store duplicates in a set, you'll either need to wrap them in some kind of holder object, or else override equals() and hashCode() of your model objects so that they do not evaluate as equivalent (and even that will fail if you are trying to store references to the same physical object multiple times).
I think you need to re-evaluate what you are trying to accomplish here, or at least explain it more clearly to us.
Upvotes: 13
Reputation: 17904
From the javadocs:
"sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one
null
element"
So if your objects were to override .equals() so that it would return different values for whatever objects you intend on storing, then you could store them separately in a Set
(you should also override hashcode() as well).
However, the very definition of a Set
in Java is,
"A collection that contains no duplicate elements. "
So you're really better off using a List
or something else here. Perhaps a Map
, if you'd like to store duplicate values based on different keys.
Upvotes: 2
Reputation: 27199
NO chance.... you can not have duplicate values in SET interface... If you want duplicates then you can try Array-List
Upvotes: 0
Reputation: 7779
I don't think so. The only way would be to use a List. You can also trick with function equals(), hashcode() or compareTo() but it is going to be ankward.
Upvotes: 0
Reputation: 6810
I don't believe that you can have duplicate values within a set. A set is defined as a collection of unique values. You may be better off using an ArrayList.
Upvotes: 1