Can someone explain why this expression is OK
TestClass[] a = {new TestClass("a")};
public List<TestClass> tall = Arrays.asList( a );
but this one is rejected by the compiler with a "Syntax error"
public List<TestClass> tall = Arrays.asList( {new TestClass("a")} );
Is shortcut syntax for declaring arrays only allowed on the right side of an array declaration?
With the exception of an explicit array initialization (eg, TestClass[] a = {new TestClass("a")};
), you cannot use the {}
notation for an array literal without calling the new
operator.
So either explicitly call the new
operator:
public List<TestClass> tall =
Arrays.asList( new TestClass[] {new TestClass("a")} );
Or better yet, use Arrays.asList
's varags notation, and drop the array initialization completely:
public List<TestClass> tall = Arrays.asList(new TestClass("a"));
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.