This site requires JavaScript, please enable it in your browser!
Greenfoot back
Josh_H
Josh_H wrote ...

2015/11/30

Incompatible types

Josh_H Josh_H

2015/11/30

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ArrayList tiles = new ArrayList();
int [] randomTiles = new int[10];
Random num = new Random();
 
for(int x = 0; x < 81; x++)
{
    tiles.add(x);
}
 
int not = 81;
for(int x = 0; x < 10; x++, not --)
{
    int index = num.nextInt(not);
    randomTiles[x] = tiles.get(index);
    tiles.remove(index);
}
I am trying to generate 10 random numbers between 0 and 80 but it is saying that the index int the line "randomTiles = tiles.get(index);" is incompatible and it says java.lang.Object can't be converted to int. Anyone know why?
danpost danpost

2015/11/30

#
Josh_H wrote...
I am trying to generate 10 random numbers between 0 and 80 but it is saying that the index int the line "randomTiles = tiles.get(index);" is incompatible and it says java.lang.Object can't be converted to int. Anyone know why?
That is correct. A List object holds references to objects -- not values. Your int values are converted to Integer object when placed within the list. There are two missing steps in your code. One is the lack of casting the object held by the list as an Integer object; the other is getting the int value from that Integer object (this step is impossible without first casting the object as an Integer object as the 'intValue' method of the Integer class will not be found, otherwise). A couple things that might help simplify your code: * the 'not' variable is unnecessary as you can use '81-x' to express the value; * you do not need to use 'get' if you are using 'remove' on the same element of the list; the 'remove' method returns the object from the list as well:
1
randomTiles[x] = ((Integer)tiles.remove(index)).intValue();
Josh_H Josh_H

2015/11/30

#
Thanks danpost
Josh_H Josh_H

2015/12/8

#
I was experimenting with different things on my program above, @danpost , and I tried taking the '.intValue()' out and my program worked just fine without it. I thought it might be because the first instance of casting already converted it to an integer, but is there another explanation?
danpost danpost

2015/12/8

#
Well, I guess it is explained best in the java tutorials. This page says the following about classes that wrap a primitive value (Number subclasses):
Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.
You need to login to post a reply.