相关疑难解决方法(0)

使用Java管理高度重复的代码和文档

高度重复的代码通常是一件坏事,并且有一些设计模式可以帮助减少这种情况.然而,由于语言本身的限制,有时它是不可避免的.以下示例来自java.util.Arrays:

/**
 * Assigns the specified long value to each element of the specified
 * range of the specified array of longs.  The range to be filled
 * extends from index <tt>fromIndex</tt>, inclusive, to index
 * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
 * range to be filled is empty.)
 *
 * @param a the array to be filled
 * @param fromIndex the index of the first element (inclusive) to be
 *        filled with the specified value
 * @param toIndex …
Run Code Online (Sandbox Code Playgroud)

java maintenance preprocessor guava

70
推荐指数
3
解决办法
5003
查看次数

Java Arrays.equals()为二维数组返回false

我只是很想知道 - 为什么Arrays.equals(double [] [],double [] [])返回false?实际上,当数组具有相同数量的元素并且每个元素是相同的?

例如,我进行了以下测试.

double[][] a,  b;
int size =5;

a=new double[size][size];
b=new double[size][size];

for( int i = 0; i < size; i++ )
    for( int j = 0; j < size; j++ ) {
        a[i][j]=1.0;
        b[i][j]=1.0;
    }

if(Arrays.equals(a, b))
    System.out.println("Equal");
else
    System.out.println("Not-equal");
Run Code Online (Sandbox Code Playgroud)

返回false并打印"不相等".

另一方面,如果我有这样的事情:

double[] a,  b;
int size =5;

a=new double[size];
b=new double[size];

for( int i = 0; i < size; i++ ){
    a[i]=1.0;
    b[i]=1.0;
} 

if(Arrays.equals(a, b))
    System.out.println("Equal");
else
    System.out.println("Not-equal");
Run Code Online (Sandbox Code Playgroud)

返回true并打印"Equal".该方法仅适用于单个尺寸吗?如果是这样,Java中的多维数组是否有类似的东西?

java arrays

39
推荐指数
1
解决办法
4万
查看次数

我可以编写一个遍历集合和数组的for循环吗?

是否有可能检查对象是带子句的数组还是集合?我想要达到的目标:

假设数组实现了Iterable,并假定Object foo可以是数组或集合,则我想使用如下代码片段:

if (foo instanceof Iterable) {
  for (Object f : (Iterable) foo) {
    // do something with f
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,数组不能转换为Iterable。它也没有实现Collection。是否还有其他可能像上述那样在一个循环中处理这两者?当然不是使用if-else if-clause和两个循环(这不是很好)。

编辑:针对这些答案。我知道isArray()方法,但是在这种情况下,

...
for (Object f : (Iterable) foo) {
...
Run Code Online (Sandbox Code Playgroud)

将失败。遗憾和代码冗余,因为尽管foreach循环可同时用于Collections和Arrays,但我必须使用两个循环。

java arrays collections

19
推荐指数
4
解决办法
2125
查看次数

标签 统计

java ×3

arrays ×2

collections ×1

guava ×1

maintenance ×1

preprocessor ×1