Java AbstractList wrap another list to create custom list and reverse an unmodifiable List

Description

Java AbstractList wrap another list to create custom list and reverse an unmodifiable List

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

public class Main {
  public static void main(String[] args) {
    String[] array = { "CSS", "HTML", "Java", "Javascript", "SQL" };

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

    List<String> reversedView = reversedView(list);
    System.out.println("Reversed : " + reversedView);
  }/*from w  w w  .jav  a 2s.com*/

  public 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();
      }
    };
  }
}



PreviousNext

Related