Connecting Tech Pros Worldwide Forums | Help | Site Map

Checking for duplicates

Newbie
 
Join Date: Aug 2007
Posts: 20
#1: Oct 29 '07
I currently have two String variables I check to find if they are duplicates:

Expand|Select|Wrap|Line Numbers
  1. String str1 = "red";
  2. String str2 = "yellow";
  3. if (str1.equals(str2)){
  4.       System.out.println("Duplicate");
  5. }
  6. else{
  7.       System.out.println("Not duplicate");
  8. }
Since red is not the same as yellow it would show "Not Duplicate".

Now how would I check 10 variables to find out if any of them are duplicates?

Expand|Select|Wrap|Line Numbers
  1. String str1 = "red";
  2. String str2 = "yellow";
  3. String str3 = "green";
  4. String str4 = "blue";
  5. String str5 = "red";
  6. String str6 = "green";
  7. String str7 = "green";
  8. String str8 = "white";
  9. String str9 = "black";
  10. String str10 = "green";
In this example red and green have duplicates.

Please advise how I can do this?

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Oct 29 '07

re: Checking for duplicates


I would use a String Array and 2 nested for...loops to iterate through the array, checking for duplicate values.

If you have them stored as str1, str2, str3,...,strN, then only way you can check for multiples is with many, many if statements (somewhere close to N^2).
Member
 
Join Date: Nov 2007
Location: ZIMBABWE
Posts: 118
#3: Nov 12 '07

re: Checking for duplicates


Every colour can have a boolean representing it e.g isRed which is false before the string red is entered. When the string is entered, the flag is set to true and when someone enters the string any other time the flag will be set to true - if its true , then duplicate should be printed.
Reply