2

I have a generic function that returns a List<?>. If it works correctly, it will return a List<LightSensor>, but I cannot directly convert the result of the function to a variable of type List<LightSensor>. How can I check if the class in the List is a LightSensor correctly? (e.g. check if List<?> = List<LightSensor>) Also, What is the best way to cast it correctly once I've checked?
BTW the class LightSensor extends Object and a version of Serializable

10
  • 2
    Perhaps you should show us your generic function. Commented Sep 19, 2013 at 0:46
  • 1
    Also, in Java, we call them "methods", not "functions". Commented Sep 19, 2013 at 0:53
  • It's nothing special, why do you need to see it? It just returns a List<?>. If you really want to see it, go here: jd.bukkit.org/rb/doxygen/df/d9a/… Commented Sep 19, 2013 at 0:55
  • 1
    @Pocketkid2 - read the "help". Inlined code should be enclosed in backticks. Commented Sep 19, 2013 at 1:02
  • 1
    @TJamesBoone - there's a better way! Commented Sep 19, 2013 at 1:03

2 Answers 2

4

How can I check if the class in the List is a LightSensor correctly? (e.g. check if List<?> = List<LightSensor>)

AFAIK, the only way to do this is to iterate the list and use instanceof LightSensor or getClass() == LightSensor.class on each element.

Also, What is the best way to cast it correctly once I've checked?

Just do a typecast, and suppress the "unchecked conversion" warning.

Sign up to request clarification or add additional context in comments.

2 Comments

Should I use Object for iterating through the List<?>?
@Pocketkid2 - ermm ... yes. You've got no choice really, 'cos that's what static typing says the element type of List<?> is.
1

Well the idiom to return a generic collection from a method is something like:

public <T> List<T> getTheList(Class<T> cls){
  // you might need the cls in here to create the list.
  ...
}

Obviously the way you use the Class<T> to generate the list is application specific. Most of the times this makes sense in the context of some class hierarchy, in which case T extends some base class or interface:

public <T extends MyBaseClassOrInterface> List<T> getTheList(Class<T> cls){
  ...
}

Again, the way you create the list is completely application dependent. If you try to keep your whole application strongly typed you might be able to avoid doing some kind of black magic to figure out the type parameter of List<?>. It's a strong code smell if you end up with code like that (unless obviously you are dealing with some legacy code). Besides, if the list is empty you are absolutely hopeless.

Comments

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.