SEARCH FOR A STRINGBUFFER OBJECT IN AN ARRAYLIST?

Monaj Singh

Total Post:41

Points:287
Posted by  Monaj Singh
 677  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Search for a StringBuffer object in an ArrayList?

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!