java - 如何确保数组中包含值?

标签 java arrays arraylist

以下是我的代码:

它用于测试素数生成器,该生成器创建并填充数组列表的前 n 个素数。在我的测试中,我创建了一个已知素数的数组,然后使用我的方法构建前 50 个 (knownPrimes.length) 素数的数组列表。然后选择一个随机数,我想断言使用我的方法 nextRandomPrime (从未知/生成的素数数组列表中选择一个数字)选择的每个素数都包含在数组knownPrimes中。我该如何做到这一点?

在伪代码中我想做的是:

assertTrue(createdPrimeList.nextRandomPrime is a value in the array knownPrimes);

这是我到目前为止所得到的:

 public void comparePrimes() {
    int[] knownPrimes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 
      31,  37,  41,  43,  47,  53,  59,  61,  67,  71, 
      73,  79,  83,  89,  97, 101, 103, 107, 109, 113, 
      127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 
      179, 181, 191, 193, 197, 199, 211, 223, 227, 229 };

    Primes createdPrimeList = new Primes (knownPrimes.length);
    for (int index = 0; index < noOfTests; index++) //noOfTests is a global variable
    {
      assertTrue( createdPrimeList.nextRandomPrime( ) IS IN knownPrimes );//line I am struggling with
    }
  }

有人可以帮我吗?

非常感谢。

最佳答案

使用二分查找。您可以使用Arrays.binarySearch(int[] array, int key) .

为了验证下一个值是否存储在 knownPrimes 中,您应该执行以下操作:

int nextValue = createdPrimeList.nextRandomPrime();
if (Arrays.binarySearch(knownPrimes, nextValue) >= 0) {
    System.out.println("The value is already stored in known primes");
}

关于java - 如何确保数组中包含值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4339269/

相关文章:

java - 从数组引用值时出现问题

java - 在任何情况下我应该在外部使用 ArrayList 上的 ensureCapacity() 吗?

java - Scala 中线程执行器池的替代品

java - 如何实现 `range()`

javascript - PHP - 单击时从项目列表中的数组调用特定变量/与 JavaScript 混合

javascript - 在 Javascript 中迭代多个数组而不使用索引

Java:迭代 2 个列表的最佳/优雅方式

android - 在 Android 中将具有特定 id 的数组列表从一个类传递到另一个类

除非指定参数类型,否则 Java 无法编译通用 lambda 参数

java - Netbeans 添加带有可视化编辑器的弹出菜单