Code first: )
/**
*
* @param arrayList the ArrayList
* @return a random object from the ArrayList
*/
public static Object randomArrayListObject(ArrayList<?> arrayList) {
Random random = new Random();
int i = random.nextInt(arrayList.size());
assert i >= 0;
assert i < arrayList.size();
return arrayList.get(i);
}
public static Class<? extends Juice> randomArrayListJuiceClass(
ArrayList<Class<? extends Juice>> arrayList) {
final Object o = randomArrayListObject(arrayList);
assert Juice.class.isAssignableFrom((Class) o);
if (Juice.class.isAssignableFrom((Class) o)) {
@SuppressWarnings("unchecked")
Class c = (Class<? extends Juice>) o;
return c;
} else throw new RuntimeException("wtf? not a Juice Class??");
}
I'm getting this warning:
Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<? extends drinks.Juice>'
I put all that monster code in randomArrayListJuiceClass()
to try to avoid such warnings but still I can't figure it out. What can I do?
My goal is just to return the (some kind of) Juice
Class without warnings... I know I'm only feeding randomArrayListJuiceClass()
some Juice
, I just have it throwing an Exception
just in case I was sloppy and fed it something else.
What should I do?
Your method for getting a random element should be generic and bind its return type to the type of the input ArrayList
public static <T> T randomArrayListObject(ArrayList<T> arrayList) {
Your other code then becomes
final Class<? extends Juice> o = randomArrayListObject(arrayList);
assert Juice.class.isAssignableFrom(o); // even this is kind of useless
return o;
Assuming your assertions are on, you won't need another exception thrown.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.