java - Why will happen strange thins,when I reuse the List Collector and put it to HashSet. -
public class leetcode3sum { public static void main(string[] args) { int[] = {-1, 0, 1, 2, -1, -4}; list<list<integer>> lists = foursum(a, 0); } public static list<list<integer>> foursum(int[] nums, int target) { if (nums == null || nums.length < 4 ) return null; int len = nums.length; list<integer> ns = new arraylist<>(); hashset<list<integer>> set = new hashset<>(); (int = 0; < len; ++i) { (int j = + 1; j < len; ++j) { (int k = j + 1; k < len; ++k) { //filter sum not equal target if (nums[i] + nums[j] + nums[k] != target) { continue; } ns.add(nums[i]); ns.add(nums[j]); ns.add(nums[k]); collections.sort(ns); system.out.println(ns); set.add(ns); system.out.println(set); ns.clear(); } } } list<list<integer>> lists = new arraylist<>(); (list<integer> s : set) lists.add(s); return lists; } } the strange result is:
[-1, 0, 1] [[-1, 0, 1]] [-1, -1, 2] [[-1, -1, 2], [-1, -1, 2]] [-1, 0, 1] [[-1, 0, 1], [-1, 0, 1]] what except is:
[-1, 0, 1] [[-1, 0, 1]] [-1, -1, 2] [[-1, -1, 2], [-1, 0, 1]] [-1, 0, 1] [[-1, -1, 2], [-1, 0, 1]] i don't want new arraylist object every time. if don't it, work will!
i read jdk1.8's resource code, think should not happen strange things. want know why ?
Comments
Post a Comment