1 /* 2 * Copyright (C) 2017 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 18 package com.android.internal.util; 19 20 import android.annotation.NonNull; 21 import android.annotation.Nullable; 22 import java.util.Objects; 23 24 /** @hide */ 25 @android.ravenwood.annotation.RavenwoodKeepWholeClass 26 public class ObjectUtils { ObjectUtils()27 private ObjectUtils() {} 28 29 /** 30 * Returns the first of two given parameters that is not {@code null}, if either is, 31 * or otherwise throws a {@link NullPointerException}. 32 * 33 * @throws NullPointerException if both {@code a} and {@code b} were {@code null} 34 */ 35 @NonNull firstNotNull(@ullable T a, @NonNull T b)36 public static <T> T firstNotNull(@Nullable T a, @NonNull T b) { 37 return a != null ? a : Objects.requireNonNull(b); 38 } 39 40 /** 41 * Nullsafe {@link Comparable#compareTo} 42 */ compare(@ullable T a, @Nullable T b)43 public static <T extends Comparable> int compare(@Nullable T a, @Nullable T b) { 44 if (a != null) { 45 return (b != null) ? a.compareTo(b) : 1; 46 } else { 47 return (b != null) ? -1 : 0; 48 } 49 } 50 51 /** 52 * Returns its first argument if non-null, and the second otherwise. 53 */ 54 @Nullable getOrElse(@ullable final T object, @Nullable final T otherwise)55 public static <T> T getOrElse(@Nullable final T object, @Nullable final T otherwise) { 56 return null != object ? object : otherwise; 57 } 58 } 59