How to change non-modifiable list in java

I am trying to modify an unmodifiable list. However, I tried to achieve it, but is it possible to update or cancel and not change the list? I know we can do it with Google Immutable List

import java.util.*;

public class ImmutableList 
 {

public static void main(String args[])
{
    String[] mylist = {"Apple","Orange","Mango","Kiwi","Banana"};
    List reverselist = new ArrayList();
    List<String> strList = Arrays.asList(mylist);
    List<String> unmodifiableList = Collections.unmodifiableList(strList);
    for(int i=unmodifiableList.size();i>0;i--)
    {
        reverselist.add(unmodifiableList.get(i-1));

    }
    List<String> reverse = Collections.unmodifiableList(reverselist);
    System.out.println(reverse);
  }

 }

In the above program, I simply go to the unmodified list from the back and put them into an array after adding this array to a new unmodified list. Can we do it better in terms of optimization?

+4
source share
3 answers

When the list is not modifiable, you can simply create a reverse view in the list.

: O (1) O (1) .

import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;

public class ReversedListViewTest
{
    public static void main(String[] args)
    {
        String[] array = {"Apple","Orange","Mango","Kiwi","Banana"};

        List<String> list = Arrays.asList(array);
        System.out.println("List         : "+list);

        List<String> reversedView = reversedView(list);
        System.out.println("Reversed view: "+reversedView);
    }

    private static <T> List<T> reversedView(final List<T> list)
    {
        return new AbstractList<T>()
        {
            @Override
            public T get(int index)
            {
                return list.get(list.size()-1-index);
            }

            @Override
            public int size()
            {
                return list.size();
            }
        };
    }

}
+2

Guava Lists.reverse(List) .

+4

This may not be the best solution, but better than by itself:

public List<T> reverseUnModList(List<T> unModListOrig) {
    List<T> tmpList = new ArrayList<T>(unModListOrig); 
    Collections.reverse(tmpList);
    return Collections.unmodifiableList(unModListOrig);
    //return tmpList; //if the result not need to be unmodifieable
}
+2
source

Source: https://habr.com/ru/post/1539100/


All Articles