Home > DeveloperSection > Forums > Search for a StringBuffer object in an ArrayList?
Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    December-22-2015 11:41 PM

 Java Java  Array List  String 
Ratings:


 1 Reply(s)
 323  View(s)
Rate this:
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-22-2015 11:57 PM

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));

Don't want to miss updates? Please click the below button!

Follow MindStick