Java 中的 Ints contains() 函数

java 8object oriented programmingprogramming更新于 2025/6/26 15:22:17

Ints 类的 contains() 函数用于检查某个元素是否存在于数组中。

以下是语法 −

public static boolean
contains(int[] arr, int target)

其中,arr 是待检查元素所在的数组。target 是待检查的元素。

以下是实现 Ints 类 contains() 方法的示例 −

示例

import com.google.common.primitives.Ints;
import java.util.*;
class Demo {
   public static void main(String[] args) {
      int[] myArr1 = { 100, 150, 230, 300, 400 };
      int[] myArr2 = { 450, 550, 700, 800, 1000 };
      System.out.println("Array 1 = ");
      for(int i=0; i < myArr1.length; i++) {
         System.out.println(myArr1[i]);
      }
      System.out.println("Array 2 = ");
      for(int i=0; i < myArr2.length; i++) {
         System.out.println(myArr2[i]);
      }
      int[] arr = Ints.concat(myArr1, myArr2);
      System.out.println("Concatenated arrays = "+Arrays.toString(arr));
      if (Ints.contains(arr, 800))
         System.out.println("Element 800 is in the array!");
      else
         System.out.println("Element 800 is not in the array!");
   }
}

输出

Array 1 =
100
150
230
300
400
Array 2 =
450
550
700
800
1000
Concatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000]
Element 800 is in the array!

相关文章