我正在刷新我的 Java 知识,并正在做一个 Codewars 练习。问题是比较两个数组的元素是否“相同”。 “相同”的含义是“b”中的元素是“a”中元素的平方,无论顺序如何。我试图做的解决方案是获取“b”中元素的平方根,并使用 Math.sqrt() 检查它是否存在于元素“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,但仍然得到相同的结果。
最佳答案
不是直接答案,而是避免此类问题的解决方法:
正如其他答案中所解释的,您的问题是强制转换问题,因为您必须处理 double
和 int
值,并且不必面对强制转换问题。
避免这种情况的一种方法是对 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);
关于java - 当使用 Math.sqrt() 作为参数时,List contains 方法返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598215/