Home java Why is the Arrays.asList () method needed?

Why is the Arrays.asList () method needed?

Author

Date

Category

Why is the Arrays.asList () method needed? What is its essence?


Answer 1, authority 100%

As follows from documentation : Builds a list based on an array. The array is then used for the internal representation of the list. This preserves the link between the list and the original array:

  • changes to the array will be reflected in the list:

    String [] a = {"foo", "bar", "baz"};
    List & lt; String & gt; list = Arrays.asList (a);
    System.out.println (list); // [foo, bar, baz]
    a [0] = "aaa";
    System.out.println (list); // [aaa, bar, baz]
    
  • changes in the list will be reflected in the array:

    String [] a = {"foo", "bar", "baz"};
    List & lt; String & gt; list = Arrays.asList (a);
    System.out.println (list); // [foo, bar, baz]
    list.set (0, "bbb");
    System.out.println (Arrays.toString (a)); // [bbb, bar, baz]
    

If the array contains objects, obviously both the array and the list will refer to the same instances:

Object [] a = {new Object (), new Object (), new Object ()};
List & lt; Object & gt; list = Arrays.asList (a);
System.out.println (a [0] == list.get (0)); // true

As already mentioned by @Oleg Chiruhin , the fact that the method takes an array as a parameter in the form of variable length arguments allows it to be used for relatively convenient initialization of lists:

List & lt; Foo & gt; list = Arrays.asList (new Foo (...), new Foo (...), new Foo (...));

compare with

List & lt; Foo & gt; list1 = new ArrayList & lt; & gt; ();
list.add (new Foo (...));
list.add (new Foo (...));
list.add (new Foo (...));

Answer 2, authority 53%

In addition to what is described in the JavaDoc, the practical essence of this method is that quite often you need to send a list to the method input, the elements of which are known in advance (for example, some set of magic constants, which is often required to quickly write TDD -tests). But there is no pretty syntax in Java for initializing an in-place list, right at the place of the call. Therefore, you can call it simply in the syntax mymethod (Arrays.asList ("Novosibirsk", "Moscow", "Kukuevo")) . Note that I was able to initialize the sheet even inside a sentence in Russian!

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions