-2
public class ListFile {
    public static void main(String[] args){
        String[] arr = {"text", "tekl"};
        List<String> list = Arrays.asList(arr);     
        List<String> listt = Arrays.asList({"text", "tttt"});
        }
}

Line 4 is totally working fine. However, line 5 gives error: "Syntax error on token ".", @ expected after this token" at column 36. Is the argument passed as {"text", "tttt"} is considered as block here?

S Kumar
  • 565
  • 6
  • 20

3 Answers3

3

When you do Type[] arr = { …, … }; that's an array initializer. It can only be used in array declarations (or in array creation expressions, i.e. new String[]{"a", "b"}).

Arrays.asList is defined to take varargs arguments (asList(T... a)), so you do not have to wrap your arguments in an array first: Arrays.asList("text", "tek1") will already implicitely create an array from your arguments and pass this to the method.

knittl
  • 216,605
  • 51
  • 293
  • 340
1

You are mixing possible correct synthax. These are the possibilities you want to specify:

List<String> listt = Arrays.asList("text", "tttt");

or

List<String> listt = Arrays.asList(new String[]{"text", "tttt"});
Andrea
  • 5,893
  • 1
  • 29
  • 53
0

You try to insert something invalid in Arrays.asList. Try to use

List<String> listt = Arrays.asList("text", "tttt");

From Java 8 javadocs

asList

@SafeVarargs

public static List asList(T... a)

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

List stooges = Arrays.asList("Larry", "Moe", "Curly");

Type Parameters:

T - the class of the objects in the array

Parameters:

a - the array by which the list will be backed

Returns:

a list view of the specified array

Ioannis Barakos
  • 1,279
  • 1
  • 11
  • 15