1

I created a set and a random number (type of int) that I want to add to my set:

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

so I tried these:

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

They all don't work so how can I add 'rand' to my set?

Holger
  • 285,553
  • 42
  • 434
  • 765
Maor Cohen
  • 936
  • 2
  • 18
  • 33
  • 1
    You should post the *complete* code. Obviously, you have a type named `Integer` in your scope, which is different to `java.lang.Integer`. According to the last error message, it is a type parameter, declared either at the method or at the class containing your code. – Holger Nov 14 '16 at 17:28
  • Possible duplicate of [Autoboxing isnt working properly](http://stackoverflow.com/questions/38464664/autoboxing-isnt-working-properly) – Tom Nov 18 '16 at 01:38

2 Answers2

1

You must create object of type Integer:

Integer intObj = new Integer(i);

being i an int type.

So in your example, it would be something like:

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(new Integer(rand));
Dez
  • 5,702
  • 8
  • 42
  • 51
  • but when I try this: mySet.add(new Integer(rand)); it doesn't work. It's written that "type parameter Integer cannot be instantiated directly". and it doesn't work even if I do this: Integer iRand = new Integer(rand); mySet.add(iRand); – Maor Cohen Nov 13 '16 at 01:03
  • ohh I just saw your edit.. so I must create MyInteger class that extends Integer for adding int to Set? – Maor Cohen Nov 13 '16 at 01:05
0

I succeeded to find a solution that solves the problem of all the collections that you try to add them a 'int' value. I created this class:

class Number {
    int number;
    Number(int num) { number = num; }
}

Then, in my code, I used it:

Number number = new Number(index); // index is int type
mySet.add(number); // adding an object into a collection is legal
Maor Cohen
  • 936
  • 2
  • 18
  • 33
  • 3
    Adding an object of your custom type `Number` to a `Set` is *not* legal. If that is accepted by the compiler, you have changed the type of your `Set` beforehand. This is kludging as it doesn’t solve your initial task of creating a `Set`. – Holger Nov 14 '16 at 17:25
  • you're right. I forgot to write it but I changed the Set type from Integer to Number. – Maor Cohen Nov 14 '16 at 22:25