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 Java Data Structures - Retired Exploring the Java Collection Framework Lists

Sina Maleki
Sina Maleki
6,135 Points

Problem

Hi everyone When I put array in to the list with below codes, I can't remove items of list.

LIst<String> lst = new ArrayLIst<String>();
lst = Arrays.asList("sina","saeed");              
lst.remove(0);  

but I've got below error after run above codes.

java.lang.UnsupportedOperationException

3 Answers

Christopher Augg
Christopher Augg
21,223 Points

Sina,

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


       public class UsingList {

        public static void main(String[] args) {
        //There were some typo's here. LIst is List and ArrayLIst is ArrayList
        List<String> lst = new ArrayList<String>();
        //lst = Arrays.asList("sina","saeed"); This makes a fixed size list

        //do the following for a non-fixed size list
        lst.add("sina");
        lst.add("saeed");
        System.out.println(lst.get(0));
        lst.remove(0); 
        System.out.println(lst.get(0));

    }

}
Sina Maleki
Sina Maleki
6,135 Points

Hi Christopher You mean if I put items into list from array, I can't modify it?

Christopher Augg
Christopher Augg
21,223 Points

You can modify it with the set method. You just can't add or remove to it when using the Arrays.asList().

Check out: http://stackoverflow.com/questions/25447502/regarding-immutable-list-created-by-arrays-aslist

Sina Maleki
Sina Maleki
6,135 Points

I've just understood. when we create a list from Arrays.asList, list items related to arrays item. e.g if I change first index of array, quickly the first item of list is change;