I wrote a program that prompts users to enter one string per line and stores it into an array. It also checks for duplicate entries as data are fed and renames those to become distinct by appending an incrementing number. Imagine that it will be used by a large number of people in some name registration event. I am concerned about how slow it will run because of all the comparisons as more and more strings are put.
About the code below, the first line scans how many times inputs will be scanned. I have yet to finish the input validation part as I noticed the above performance issue halfway through writing it.
How can I reduce the number of comparisons and make the program run faster?
import java.util.*;
public class Temp {
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] names = new String[n];
int namesPoint = 0;
for(int i=0;i<n;i++) {
String name = scanner.next();
int k=0;
boolean dupe = false;
for(int j=0;j<namesPoint;j++) {
if(names[j].equals(name)) {
dupe=true;
break;
}
}
if(dupe) {
String newname="";
while(dupe){
dupe=false;
k++;
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(k);
newname = sb.toString();
for(int j=0;j<namesPoint;j++) {
if(names[j].equals(newname)) {
dupe=true;
break;
}
}
}
System.out.printf("%s\n",newname);
names[namesPoint]=newname;
namesPoint++;
k=0;
}else {
names[namesPoint]=name;
namesPoint++;
System.out.printf("OK\n");
}
}
scanner.close();
}
}