1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.car.internal.util; 18 19 import android.annotation.NonNull; 20 21 import java.util.AbstractList; 22 import java.util.ArrayList; 23 import java.util.Arrays; 24 import java.util.Collections; 25 import java.util.List; 26 27 // Copy from frameworks/base/core/java/com/google/android/collect 28 /** 29 * Provides static methods for creating {@code List} instances easily, and other 30 * utility methods for working with lists. 31 * 32 * @hide 33 */ 34 public class Lists { 35 36 /** 37 * Creates an empty {@code ArrayList} instance. 38 * 39 * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use 40 * {@link Collections#emptyList} instead. 41 * 42 * @return a newly-created, initially-empty {@code ArrayList} 43 */ newArrayList()44 public static <E> ArrayList<E> newArrayList() { 45 return new ArrayList<E>(); 46 } 47 48 /** 49 * Creates a resizable {@code ArrayList} instance containing the given 50 * elements. 51 * 52 * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the 53 * following: 54 * 55 * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} 56 * 57 * <p>where {@code sub1} and {@code sub2} are references to subtypes of 58 * {@code Base}, not of {@code Base} itself. To get around this, you must 59 * use: 60 * 61 * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} 62 * 63 * @param elements the elements that the list should contain, in order 64 * @return a newly-created {@code ArrayList} containing those elements 65 */ newArrayList(E... elements)66 public static <E> ArrayList<E> newArrayList(E... elements) { 67 int capacity = (elements.length * 110) / 100 + 5; 68 ArrayList<E> list = new ArrayList<E>(capacity); 69 Collections.addAll(list, elements); 70 return list; 71 } 72 73 /** 74 * Converts the array of primitive integers passed as argument into an unmodifiable list of 75 * {@code java.lang.Integer}. 76 */ 77 @NonNull asImmutableList(@onNull int[] ints)78 public static List<Integer> asImmutableList(@NonNull int[] ints) { 79 int[] unmodifiableInts = Arrays.copyOf(ints, ints.length); 80 return new AbstractList<>() { 81 public Integer get(int i) { 82 return unmodifiableInts[i]; 83 } 84 public int size() { 85 return unmodifiableInts.length; 86 } 87 }; 88 } 89 } 90