2

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?

2
  • 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. Commented Nov 14, 2016 at 17:28
  • Possible duplicate of Autoboxing isnt working properly Commented Nov 18, 2016 at 1:38

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

2 Comments

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);
ohh I just saw your edit.. so I must create MyInteger class that extends Integer for adding int to Set<Integer>?
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

2 Comments

Adding an object of your custom type Number to a Set<Integer> 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<Integer>.
you're right. I forgot to write it but I changed the Set type from Integer to Number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.