我創建了一個集和隨機數(類型爲int),我要添加到我的一套:如何將int值添加到設置<Integer>(HashSet <Integer>)?
private Set<Integer> mySet = new HashSet<Integer>(numElements); // capacity of 'numElements'
Random r = new Random();
int rand = r.nextInt(maxVal - minVal + 1) + minVal;
mySet.add(rand); // error: cannot convert int to Integer
,所以我嘗試了這些:
1. mySet.add(rand); // error: no suitable method found for add(int)
2. mySet.add(Integer.valueOf(rand)); //error: cannot find symbol method valueOf(int)
3. mySet.add(new Integer(rand)); // error: type parameter Integer cannot be instantiated directly
他們都沒有工作,所以我怎樣才能將「rand」添加到我的設置中?
你應該張貼在*完整*代碼。顯然,在你的作用域中有一個名爲'Integer'的類型,它與'java.lang.Integer'不同。根據最後一條錯誤消息,它是一個類型參數,在方法或包含代碼的類中聲明。 – Holger
可能重複[Autoboxing工作不正常](http://stackoverflow.com/questions/38464664/autoboxing-isnt-working-properly) – Tom