1 /*
2  * Copyright (C) 2021 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.permission.util;
18 
19 import android.annotation.Nullable;
20 
21 import java.util.Objects;
22 
23 /**
24  * Array utilities.
25  */
26 public final class ArrayUtils {
ArrayUtils()27     private ArrayUtils() {}
28 
29     /**
30      * @see java.util.List#contains(Object)
31      */
contains(@ullable T[] array, T value)32     public static <T> boolean contains(@Nullable T[] array, T value) {
33         return indexOf(array, value) != -1;
34     }
35 
36     /**
37      * Get the first element of an array, or {@code null} if none.
38      *
39      * @param array the array
40      * @param <T> the type of the elements of the array
41      * @return first element of an array, or {@code null} if none
42      */
firstOrNull(@ullable T[] array)43     public static <T> T firstOrNull(@Nullable T[] array) {
44         return !isEmpty(array) ? array[0] : null;
45     }
46 
47     /**
48      * @see java.util.List#indexOf(Object)
49      */
indexOf(@ullable T[] array, T value)50     public static <T> int indexOf(@Nullable T[] array, T value) {
51         if (array == null) {
52             return -1;
53         }
54         final int length = array.length;
55         for (int i = 0; i < length; i++) {
56             final T element = array[i];
57             if (Objects.equals(element, value)) {
58                 return i;
59             }
60         }
61         return -1;
62     }
63 
64     /**
65      * @see java.util.List#isEmpty()
66      */
isEmpty(@ullable T[] array)67     public static <T> boolean isEmpty(@Nullable T[] array) {
68         return array == null || array.length == 0;
69     }
70 }
71