1/*
2 * Copyright (C) 2012 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
17package com.android.inputmethod.latin.common;
18
19import com.android.inputmethod.annotations.UsedForTesting;
20
21import java.util.ArrayList;
22import java.util.Collection;
23import java.util.Map;
24
25import javax.annotation.Nonnull;
26import javax.annotation.Nullable;
27
28/**
29 * Utility methods for working with collections.
30 */
31public final class CollectionUtils {
32    private CollectionUtils() {
33        // This utility class is not publicly instantiable.
34    }
35
36    /**
37     * Converts a sub-range of the given array to an ArrayList of the appropriate type.
38     * @param array Array to be converted.
39     * @param start First index inclusive to be converted.
40     * @param end Last index exclusive to be converted.
41     * @throws IllegalArgumentException if start or end are out of range or start > end.
42     */
43    @Nonnull
44    public static <E> ArrayList<E> arrayAsList(@Nonnull final E[] array, final int start,
45            final int end) {
46        if (start < 0 || start > end || end > array.length) {
47            throw new IllegalArgumentException("Invalid start: " + start + " end: " + end
48                    + " with array.length: " + array.length);
49        }
50
51        final ArrayList<E> list = new ArrayList<>(end - start);
52        for (int i = start; i < end; i++) {
53            list.add(array[i]);
54        }
55        return list;
56    }
57
58    /**
59     * Tests whether c contains no elements, true if c is null or c is empty.
60     * @param c Collection to test.
61     * @return Whether c contains no elements.
62     */
63    @UsedForTesting
64    public static boolean isNullOrEmpty(@Nullable final Collection c) {
65        return c == null || c.isEmpty();
66    }
67
68    /**
69     * Tests whether map contains no elements, true if map is null or map is empty.
70     * @param map Map to test.
71     * @return Whether map contains no elements.
72     */
73    @UsedForTesting
74    public static boolean isNullOrEmpty(@Nullable final Map map) {
75        return map == null || map.isEmpty();
76    }
77}
78