使用Math.sqrt()作为参数时,列表包含方法返回false

时间:2019-06-14 12:27:27

标签: java arraylist contains math.sqrt

我正在刷新我的Java知识,并从事代码战的练习。问题是如果元素“相同”,则比较两个数组。 “相同”的含义是,“ b”中的元素是“ a”中平方的元素,而与顺序无关。我尝试执行的解决方案是使用Math.sqrt()获取元素“ b”的平方根,并检查元素“ a”中是否存在该元素。但是,当我将其用作contains()的参数时,它总是返回false。

因此,要检查元素“ b”的平方根是否确实存在于“ a”中,我尝试了一个简单的if-else检查特定元素。但是,当我将它与Math.sqrt()合并时,就会出现问题。

这是集合a和b的元素

int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};

我已转换为列表

List<Integer> setAList = Arrays.stream(setA)//int[] setA - parameter of a function
                                                    .boxed()
                                                    .collect(Collectors.toList());
List<Integer> setBList = Arrays.stream(setB)//int[] setB - parameter of a function
                                                    .boxed()
                                                    .collect(Collectors.toList());

我将数组转换为List以利用contains()方法。 这是我尝试检查特定元素时的代码

double sqrd = Math.sqrt(setBList.get(6));
return setAList.get(5) == sqrd ? true : false;

这给出了预期的结果-是。 现在是我将其合并到for循环中的代码

boolean same = true;

for(int indexB : setB) {
    same = setAList.contains(Math.sqrt(indexB)) ? true : false; 
    System.out.println(Math.sqrt(indexB) + " " + same);

}

这是结果

11.0 false
121.0 false
144.0 false
19.0 false
161.0 false
19.0 false
144.0 false
19.0 false
false

起初,我虽然问题可能是由于数据类型引起的,但我尝试将double转换为int,但仍然得到相同的结果。

3 个答案:

答案 0 :(得分:2)

不是直接的答案,而是一种避免此类问题的解决方法:

如其他答案所述,您的问题是强制转换问题,因为您必须处理doubleint值,而不必面对强制转换问题。

避免这种情况的一种方法是对A中的值求平方而不是计算B中的值的平方根。这样一来,您只能处理int个值

int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};

// Make a list containing the squares out of the b array
List<Integer> squares = Arrays.stream(b)
    .boxed()
    .collect(Collectors.toList());

// square all the values in B,
// and check that all the resultant values are present in the squares list
boolean same = Arrays.stream(a) // Stream<Integer> containing values in array a
    .map(i -> i* i) // Stream<Integer> containing values in array a squared
    .allMatch(squares::contains); // reduce to a boolean insuring that all values in the Stream<Integer> are present in the squares list

System.out.println(same);

答案 1 :(得分:1)

setAList.get(5) == sqrd由于setAList.get(5)中的the widening primitive conversion(是int)到double而给您带来预期的结果。

如果您有setAList.contains(Math.sqrt(indexB)),则需要手动进行投射:setAList.contains((int)Math.sqrt(indexB))

答案 2 :(得分:0)

contains()一样,查找精确浮点值通常是一个坏主意,因为浮点值的精度有限。您可以尝试一下,看看Math.sqrt( number ) * Math.sqrt( number )number的哪些数字不相同:

for (int i = 0; i < 100; i++) {
  final double r = Math.sqrt(i);
  final double s = r * r;
  if (s != i) {
    System.out.println(i + " != " + s);
  }
}

(从测试的100个数字中打印出51个不等根的平方。)