generic-method

Java generic methods in generics classes

夙愿已清 提交于 2019-11-26 09:25:50
问题 If you create a generic class in Java (the class has generic type parameters), can you use generic methods (the method takes generic type parameters)? Consider the following example: public class MyClass { public <K> K doSomething(K k){ return k; } } public class MyGenericClass<T> { public <K> K doSomething(K k){ return k; } public <K> List<K> makeSingletonList(K k){ return Collections.singletonList(k); } } As you would expect with a generic method, I can call doSomething(K) on instances of

Why can this generic method with a bound return any type?

∥☆過路亽.° 提交于 2019-11-26 09:00:07
问题 Why does the following code compile? The method IElement.getX(String) returns an instance of the type IElement or of subclasses thereof. The code in the Main class invokes the getX(String) method. The compiler allows to store the return value to a variable of the type Integer (which obviously is not in the hierarchy of IElement ). public interface IElement extends CharSequence { <T extends IElement> T getX(String value); } public class Main { public void example(IElement element) { Integer x

Combining Raw Types and Generic Methods

非 Y 不嫁゛ 提交于 2019-11-26 01:45:45
问题 Here\'s a question, this first code listing compiles just fine (JDK 1.6 | JDK 1.7): ArrayList<String> a = new ArrayList<String>(); String[] s = a.toArray(new String[0]); However, if I declare the List reference as a raw type: ArrayList a = new ArrayList(); String[] s = a.toArray(new String[0]); I get a compiler error saying the String[] is required but Object[] was found. This means my compiler is interpreting the generic method as returning Object[] despite of receiving a String[] as its