The following code compiles and runs without problem:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
if(nums.length==0) return new ArrayList<>(res);
Arrays.sort(nums);
for(int i=0; i<nums.length-2;i++){
int j =i+1;
int k = nums.length-1;
while(j<k){
int sum = nums[i]+nums[j]+nums[k];
if(sum==0)res.add(Arrays.asList(nums[i],nums[j++],nums[k--]));
else if ( sum >0) k--;
else if (sum<0) j++;
}
}
return new ArrayList<>(res);
}
}
I'm baffled with this line of code
res.add(Arrays.asList(nums[i],nums[j++],nums[k--]))
res is of type HashSet<List<Integer>>, and Arrays.asList returns value of type ArrayList (not java.util.ArrayList, but an internally defined class according to java 8 source code, which also implements java.util.List)
Why DOESN'T adding ArrayList instance to a collection of List raise exception?
Although the former is subtype of latter, as far as I know the adding operation should not be allowed because HashSet<ArrayList> is not subtype of Set<List>?