I have the list of string arrays which may have duplicate entries. I want to get the unique list from these values.
I have a list of string arrays with each array having two String values.
Sample string array values:
{"error message 1", "fail"}
{"error message 2", "N/A"}
{"error message 1", "fail"} // duplicate
{"error message 2", "fail"}
I get the "error message 1" and "fail" strings from JSON elements individually and I add them to a String array object. Now I want the unique combination of this array. So, if I had the above 4 arrays, I want to have the list of only three unique entries.
From the internet search, I drilled down to use the HashSet for my use case (The order does not matter). However, the HashSet adds all 4 entries to the set. I even tried to use the 'contains' to check if the object already exists, but that did not work either. I believe, this is because the contains method is comparing the 'reference' and not the 'value'. Is this the reason that the HashSet is adding duplicate values?
My code to add these String arrays to HashSet is
Set<String[]> uniqueSet = new HashSet<String[]>();
if(!uniqueSet.contains(new String[] {errorMessage,result})) // I get errorMessage and result as separate Strings
uniqueSet.add(new String[] {errorMessage,result}); // I expect to have only 3 values here in the uniqueSet. But it adds all 4.
From answers for related questions on SO, I understand that hashcode and equal methods have to be overwritten if needed. But, I'm not sure how would I do that in my case if that is what I'm missing?
Also, let me know if you have any other suggestions to better store String arrays uniquely.
Regards,
Rumit