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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With