Richa Bhuwania
Richa Bhuwania

Reputation: 180

HashSet not returning expected output

I want to store unique lists, so I am using HashSet. But, I am not getting desired output. Here is my code, Could you tell me what is going wrong?

 public List<List<Integer>> threeSum(int[] nums) {
        
        Set<List<Integer>> res = new HashSet<>();
        
        for(int i = 0; i< nums.length; i++){
            
            int target = 0-nums[i];
            Set<Integer> neg = new HashSet<>();
            
            for(int j = i+1 ; j<nums.length; j++){
                
                int rem = target - nums[j];
                if(neg.contains(nums[j])){
                    res.add(new ArrayList<>(Arrays.asList(nums[i], rem, nums[j])));
                }
                else{
                    neg.add(rem);
                }
                
            }
        }
        System.out.println(res);
        return new ArrayList<>(res);
        
    }

Here my nums is [-1,0,1,2,-1,-4]. My output is [[-1,2,-1],[0,1,-1],[-1,0,1]]. Why am I getting both [0,1,-1] and [-1,0,1] into res as both contain the same elements. I what only one of these? What should I do?

Upvotes: 0

Views: 102

Answers (2)

Andy Turner
Andy Turner

Reputation: 140318

From the Javadoc of List.equals:

Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.

So, [0,1,-1] and [-1,0,1] aren't equal, despite containing the same elements, because they aren't in the same order.

The easiest way to solve this would be to sort the list:

res.add(Stream.of(nums[i], rem, nums[j]).sorted().collect(toList()));

Upvotes: 1

Doga Oruc
Doga Oruc

Reputation: 816

You can sort the List before adding to the Set so they will be in the same order.

Upvotes: 0

Related Questions