Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
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
List<?>
List<LightSensor>
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
List<?> = List<LightSensor>
Is there something that can do this in Ruby?
a = 'astring'[0..[5,'astring'.length].min]
Can anything take that string and generate a integer from it? In Python I could use:
int(a,36)
The output would be "18141102".
如何检查 List 中的类是否正确是 LightSensor?(例如检查是否List<?> = List<LightSensor>)
AFAIK,这样做的唯一方法是迭代列表并在每个元素上使用instanceof LightSensor或。getClass() == LightSensor.class
instanceof LightSensor
getClass() == LightSensor.class
另外,一旦我检查过,正确投射它的最佳方法是什么?
只需进行类型转换,并抑制“未经检查的转换”警告。
从方法返回泛型集合的习惯用法类似于:
public <T> List<T> getTheList(Class<T> cls){ // you might need the cls in here to create the list. ... }
显然,您使用Class<T>生成列表的方式是特定于应用程序的。大多数情况下,这在某些类层次结构的上下文中是有意义的,在这种情况下,T扩展了某些基类或接口:
Class<T>
T
public <T extends MyBaseClassOrInterface> List<T> getTheList(Class<T> cls){ ... }
同样,您创建列表的方式完全取决于应用程序。如果您尝试使整个应用程序保持强类型,您可能能够避免使用某种黑魔法来找出List<?>. 如果您最终得到这样的代码(除非您显然正在处理一些遗留代码),那么这是一种强烈的代码气味。此外,如果列表是空的,你绝对没有希望。