0

1) if I set

int[] set1 = new int[]{1, 2};
int[] set2 = new int[]{1, 2};

how come when I pass them as strings using

System.out.println(Arrays.toString(set1) == Arrays.toString(set2));

it returns false?

2) Is there any way to compare equality of entire arrays without looping through each index of the array?

dbconfession
  • 1,147
  • 2
  • 23
  • 36

3 Answers3

9
  1. Strings are Objects, so they should be compared using equals:

    System.out.println(Arrays.toString(set1).equals(Arrays.toString(set2))); //prints true
    
  2. Use Arrays#equals to compare arrays, note that the arrays must have the same length and the items must be equals: == for primitives (int, long ...) and equals for Object references).

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
4
  1. == compares string references, not values. Use str1.equals(str2). (more information on this here; it basically compare whether the actual objects are the same, not the string content)

  2. No, naturally if you want to know if each element is the same you'll have to loop through all of them. Arrays#toString does this behind the scenes also (how else would it get a string representation?).

Sidenote: converting an array to a string introduces a lot of unnecessary overhead (string manipulation, etc.). You should probably just loop through and compare elements, or create a helper method (or use a built-in one like Arrays#equals).

Community
  • 1
  • 1
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • thanks. the string conversion was a work-around to see if two arrays were equal without having to loop through each index. This of course was before you guys indicated that I could use Arrays.equals(). What does Arrays#equals do as opposed to Arrays.equals? – dbconfession Feb 13 '14 at 14:41
  • @Stuart `#` is simply the commonly used notation for referencing a method. They mean the same thing. – tckmn Feb 13 '14 at 17:31
2

Use Arrays.equals to compare arrays and see this for Strings comparisons.

Community
  • 1
  • 1
Camilo
  • 1,889
  • 2
  • 17
  • 16