I found a 'unusual' generic syntax such as:
Arrays.<String>asList(...); Collections.<String>emptyList();
Obviously, the results of the methods are generic. Is such syntax for type checking? An Object
array cannot be an argument to Arrays.<String>asList(...)
.
The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.
How is Arrays. asList() different than the standard way of initialising List? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.
asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.
Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it. The list will throw an UnsupportedOperationException if any resize operation is performed on it.
<typearg>methodname
is the syntax for explicitly specifying the type argument for a generic method
When you use a generic class, you usually have to specify the type argument (e.g. String
):
ArrayList<String> list = new ArrayList<String>();
With a generic method, you don't usually pass a type argument:
public static <T> void foo(T param) { } ... String s = ...; MyClass.foo(s);
You'll notice no where did we did the code explicitly specify we want the String
version of foo
, i.e. there was no explicit type argument <String>
specified like we saw when using a generic class (List<String>
).
The compiler is doing some compiler magic to infer the generic type argument based on context. This is a great thing and very powerful.
However, occassionally the compiler can't infer the type arguments automatically:
public static <T> void bar() { T myLocalVar = ...; ... } MyClass.bar();
What concrete version of bar
are we trying to invoke, i.e. what is the type argument for this call? Well, the compiler doesn't either. We have to explicitly state the type argument, just like we normally do when using a generic class:
MyClass.<String>bar();
Also see:
Aside: it may be worth mentioning that the Java 7 will be adding the so-called diamond operator to allow us to have the compiler to infer the type arguments when using generic classes now too:
ArrayList<String> list = new ArrayList<String>();
becomes
ArrayList<String> list = new ArrayList<>();
What is the point of the diamond operator (<>) in Java 7?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With