Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a StringBuffer object in an ArrayList?

Tags:

java

Following is the code snippet I am working with.

Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
ArrayList<StringBuffer> al = new ArrayList<StringBuffer>();
while (N-- > 0) {
   str = new StringBuffer(sc.next());
   if (al.contains(str)) {
       System.out.println("Duplicate value " + str);
   } else {
       al.add(str);
   }    
}

If the input is: 4

abc

fgh

dfg

abc

It is showing blank output when the expected output is:

Duplicate value abc

Where am I going wrong here?

like image 588
Satyajit Patnaik Avatar asked Feb 09 '23 06:02

Satyajit Patnaik


1 Answers

StringBuffer doesn't override Object's equals, so when you search if your List contains a certain StringBuffer instance, you are checking if the exact reference appears in the List.

You could use a HashSet<String> to avoid duplicates, since String overrides equals, and then (if you must) create a List<StringBuffer> from the elements of the HashSet.

BTW, StringBuilder is more efficient than StringBuffer (which should only be used if you plan to access it from multiple threads).

Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
ArrayList<StringBuffer> al = new ArrayList<StringBuffer>();
Set<String> uniques = new HashSet<>();
while (N-- > 0) {
   uniques.add(sc.next());
}
for (String s : uniques)
    al.add (new StringBuffer(s));

If you have to report the duplicates, a small change will be required :

Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
ArrayList<StringBuffer> al = new ArrayList<StringBuffer>();
Set<String> uniques = new HashSet<>();
while (N-- > 0) {
   String str = sc.next();
   if (!uniques.add(str))
       System.out.println("Duplicate value " + str);
}
for (String s : uniques)
    al.add (new StringBuffer(s));
like image 57
Eran Avatar answered Feb 13 '23 23:02

Eran