简体   繁体   English

比较Java中char数组的两个区域,而无需创建新对象

[英]Compare two regions of char array in Java without creating new objects

Is there a way to compare two regions of a char array in Java (or of two different arrays) without creating new objects in the heap? 有没有一种方法可以比较Java中char数组(或两个不同数组)的两个区域,而无需在堆中创建新对象?

I know I can do something like this: 我知道我可以做这样的事情:

char[] region1 = Arrays.copyOfRange(bigbuffer,0,100);
char[] region2 = Arrays.copyOfRange(bigbuffer,100,200);

if (Arrays.equals(region1,region2))
   System.out.printf("Equal");

But that will create two objects that later have to be garbage collected and traverse the array buffer twice. 但这将创建两个对象,这些对象随后必须被垃圾回收并遍历两次数组缓冲区。 It would be so much better if there were a function that could just compare the two regions. 如果有一个可以比较两个区域的函数,那就更好了。 I imagine something like this: 我想象这样的事情:

if (Arrays.compareRegions(bigBuffer,0,100,bigBuffer,100,200)==0)
    System.out.printf("Equal");

Is there such a thing in Java? Java中有这样的事情吗?

You don't have to create new arrays - a single for loop is enough. 您不必创建新的数组-一个for循环就足够了。

for(int i=0; i < 100; i++) {
   if (bigbuffer[i] != bigbuffer[i+100]) {
       System.out.println("Not Equal");
       break;
   }
}

Have had a quick search and seems no built-in solution in at least Java and most famous helper libraries (Commons Lang and Guava). 进行了快速搜索,并且至少在Java和最著名的帮助程序库(Commons Lang和Guava)中似乎没有内置的解决方案。

It should be trivial to write one yourself. 自己写一个书应该很简单。 Here is one sample (in psuedo-code) that do a equal comparison (instead of compare). 这是一个进行伪比较(而不是比较)的示例(伪代码)。 Enhance it to fit your needs 增强它以满足您的需求

public static <T> boolean arrayEquals(T[] arr1, int startIndex1, T[] arr2, int startIndex2, int lengthToCompare) {
    if (arr1 == null || arr2 == null) {
        throws new NullPointerException();
    }
    if (arr1.length - lengthToCompare < startIndex1 
      || arr2.length - lengthToCompare < startIndex2) {
        throw new ArrayIndexOutOfBoundException();
    }
    // some extra checking like startIndex > 0 etc.

    // This is the real logic anyway
    for (int i = 0; i < lengthToCompare; ++i) {
        if (! Objects.equals(arr1[startIndex + i], arr2[startIndex2 + i]) {
            return false;
        }
    }
    return true;
}

Another approach which only create several small objects in heap, if you are not dealing with primitive-type-array, is: 如果不处理原始类型数组,另一种仅在堆中创建几个小对象的方法是:

Foo[] arr1 = ....;
Foo[] arr2 = ....;

if (Arrays.asList(arr1).subList(0,100).equals(
        Arrays.asList(arr2).subList(100,200)) {
    ....
}

This relies on the property that: 这取决于以下属性:

  1. Arrays.asList() returns a List impl which internally backed-up by the input array Arrays.asList()返回一个List Arrays.asList()式方法由输入数组内部备份
  2. subList() returns a view of the original list, not a copy subList()返回原始列表的视图,而不是副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM