简体   繁体   中英

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?

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?

You don't have to create new arrays - a single for loop is enough.

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).

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
  2. subList() returns a view of the original list, not a copy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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