FiftySentos FiftySentos - 1 month ago 17
Java Question

Simplifying Code for Hashset Duplicate Detector

Here is the code I have that checks reads a film into a hashset and detects whether or not the film contains duplicate.

public static void main(String args[]) throws Exception
{
boolean hasDuplicate = false;
Set<String> set = new HashSet<String>();
BufferedReader list = new BufferedReader( new FileReader(args[0]));
while(list.ready() && (hasDuplicate == false)){
set.add(list.readLine());
if(set.contains(list.readLine())) hasDuplicate = true;
}
if(hasDuplicate == true){
System.out.println("NOT UNIQUE");
}else{
System.out.println("UNIQUE");
}
list.close();
}


Is there a way for me to simplify

while(list.ready() && (hasDuplicate == false)){
set.add(list.readLine());
if(set.contains(list.readLine())) hasDuplicate = true;
}


so that I only need to call for the hashset once?

Answer

The add method returns true if the item wasn't already in the Set. So you can simply call and just chech the result:

while(list.ready() && (hasDuplicate == false)){                         
    if (!set.add(list.readLine()))
         hasDuplicate = true;                          
  }

Secondly the original code wouldn't work anyway because the line was read twice and used only once for adding and once for checking. In other words it ignored half of the input.

Comments