Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Arrays.asList() question !

Hey folks,

can someone explain this line of code to me:

List<String> arrayFirstNamesAsArray = Arrays.asList("Fat","Buddy","Sticky");

Here we have a List interface on the declaration side and then I am lost ....

What makes Arrays .... ?

Thx

Grigorij

3 Answers

List is an interface. It can hold a reference to different types of List implementations (i.e. ArrayList).

The Arrays Class provides methods for manipulating arrays. The asList() method is one such method that returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

Therefore, the code you provided:

List<String> arrayFirstNamesAsArray = Arrays.asList("Fat","Buddy","Sticky");

Arrays.asList returns a fixed sized list where arrayFirstNameAsArray holds a reference to. Nothing can be added to or removed from the list that would change its size. However, you can still change elements within the list.

Example:

List<String> arrayFirstNamesAsArray = Arrays.asList("Fat","Buddy","Sticky");

        // Attempting to add something causes an exception.
        // Uncomment next line to see this.
        //arrayFirstNamesAsArray.add("Dork");

        System.out.println(arrayFirstNamesAsArray);

        // You can still change elements though.
        arrayFirstNamesAsArray.set(0, "Ugly");

        System.out.println(arrayFirstNamesAsArray);

Hope this helps.

Regards,

Chris

Hey Grigorij,

I understand what your confused about and this confused me as well in the start. So you understand how we want to create a List with only strings on the left side. you might be wondering why we didnt just do

List<String>arrayFirstNamesAsArry = new List<String>();

that creates a new list and then we can manually add all the strings that are on the right. but what we want to do is to create a list with all those things already in the list. think of it as a premade list. in order to do this we create an array and then convert it to a list. thats because we cant directly create a premade list. so we use Array.asList("strings", "strings") as a way to do what we want. that way we now have have a prepopulated list that acts as a fixed array. we only change elements in the list but cannot add.

hope that helped

kevin

Please let me know if I am understanding what you are saying correctly when you state, "that way we now have a prepopulated list and we can can add things further to a list". When Arrays.asList is called, the fixed list it creates and returns a reference to has the limitations of the array's size. Therefore, the list cannot have anything added to it. You can test this by using the provided code I have in my post. It will give you an Exception in thread "main" java.lang.UnsupportedOperationException.

One way to allow you to add more to the List would be to create a new ArrayList and pass in the Arrays.asList

List<String> arrayFirstNamesAsArray = new ArrayList<String>(Arrays.asList("Fat","Buddy","Sticky"));

Now the add method will work.

Again, please let me know if I misunderstood what you meant though.

Regards,

Chris

Hey Christopher,

For the longest time I've believed that we can add elements to it but now I realize I was wrong. What I'm wondering now is why would you use Arrays.asList? I believe the whole point of List's is to make a flexible array but by using Arrays.asList, we are essentially taking away one of the big advantages of using lists. Why wouldn't we just create an array instead of creating a list that acts like an array. Are there any advantages doing so?

Thanks,

Kevin

Kevin,

I do not know all of the pros and cons to be honest. However, I can provide my understanding of the topic and ask that if anyone else can provide more insight, it would be appreciated.

It is my understanding that the Arrays.asList method is considered as a way to link arrays to Lists in order to adopt most of the List functionality on arrays (i.e. Obviously not add/remove). While the List returned is a fixed sized list, it is mutable since you can still change its elements. You can set a specific element or use other list functionality like Collections.shuffle or sort. For example, it is an easy way to shuffle a fixed list like a list of 52 cards. Furthermore, there are many arguments that suggest that it is a mistake to use Arrays.asList without wrapping it within an ArrayList as I showed before:

List<String> arrayFirstNamesAsArray = new ArrayList<String>(Arrays.asList("Fat","Buddy","Sticky"));

That way, if you are going to get a list, it will be one you can add/remove to and from.

Of course, it is important to also to note that Arrays.asList does not work with arrays holding primitive data types like int[], double[], etc. You have to use Integer[], Double[], or other wrapper objects just like all Lists require. For example, the code I provided in my previous post used the String object. Therefore, time complexity can become an issue if you need a lot more than 52 items. For example, when dealing with large amounts of numbers, each number for an Integer type requires an instance of an Integer object to be instantiated. One could see how this would take up more memory and lead to time complexity issues as opposed to just using a primitive int array.

Therefore, I would say that primitive data type arrays should be used whenever time complexity is an issue and you do not need List functionality.

I created a small program for an empirical analysis of timing the differences between setting numbers to a primitive array and setting numbers to an ArrayList of Integers. Just remember to comment out one or the other methods to get the time it takes to complete each of them. Also, you can try out different array sizes by changing TEST_SIZE.

APP.java
import java.util.ArrayList;
import java.util.List;

public class APP {

    private static final int TEST_SIZE = 10000000;
    private int[] mNumbers = new int[TEST_SIZE];

    // Lists have to use wrapper objects
    private List<Integer> mNumberList = new ArrayList<Integer>();


    public APP() {
        System.out.println("Creating myApp");
        System.out.println("Initializing primitive array...");
        initializeArray();
        System.out.println("Initialization of primitive array completed.");
        System.out.println("Initializing ArrayList.");
        initializeArrayList();
        System.out.println("Initialization of ArrayList completed.");
    }

    private void initializeArray() {
        for (int i = 0; i < TEST_SIZE; i++) {
            mNumbers[i] = i;
        }
    }

    private void initializeArrayList() {
        for (int i = 0; i < TEST_SIZE; i++) {
            mNumberList.add(i);
        }
    }

    public void methodToTimeArray() {       
        for (int i = 0; i < TEST_SIZE; i++) {
            mNumbers[i] = (i * 2);
        }
    }

    public void methodToTimeArrayList() {

        for (int i = 0; i < TEST_SIZE; i++) {
            mNumberList.set(i, i * 2);
        }
    }

    public static void main(String[] args) {


        APP myApp = new APP();      
        long startTime = System.nanoTime();
        System.out.println("Start time of test: " + startTime + " ms");


        // Comment out one of the following methods in order to test the other:     

        myApp.methodToTimeArray();
        //myApp.methodToTimeArrayList();


        long endTime = System.nanoTime();
        System.out.println("End time of test: " + endTime + " ms"); 

        long duration = (endTime - startTime);
        System.out.println("Time: " + (double) duration / 1000000000.0 + " Seconds");


    }
}

Hope this helps.

Regards,

Chris

Hey Christopher, hey Kevin,

thank you so much!!!!

I will read yoar post at least ten time to get the point ....

The topic is so confusing ... but I will stay focused .. I promise

Grigorij