Java的数组类型有一些特性值得注意,而如果经常使用数组类型,有必要了解java.util.Arrays这个类,它提供了几个有用的方法,下 边是一段代码,使用了这个类的一些方法:
int[] a1 = {1,2,3,4,5};
int[] a2 = {1,2,3,4,5};
System.out.println( "a1 == a2:\t" + (a1 == a2));
System.out.println( "a1.equals(a2):\t" + (a1.equals(a2)));
System.out.println( "Arrays.equals(a1, a2):\t" + Arrays.equals(a1, a2));
int hash1 = a1.hashCode();
int hash2 = a2.hashCode();
System.out.println( "hash1 == hash2:\t"+(hash1==hash2));
int _hash1 = Arrays.hashCode(a1);
int _hash2 = Arrays.hashCode(a2);
System.out.println( "Arrays.hashCode(a1) == Arrays.hashCode(a2):\t"+(_hash1==_hash2));
String s1 = a1.toString();
String s2 = a2.toString();
System.out.println( "s1="+s1+",s2="+s2);
String _s1 = Arrays.toString(a1);
String _s2 = Arrays.toString(a2);
System.out.println( "_s1="+_s1+",_s2="+_s2);
一般的建议是使用Arrays.equals,Arrays.hashCode,Arrays.toString方法,不然依赖数组的 hashCode和equals功能的程序可能会失败。
下边是运行的结果:
a1 == a2:false
a1.equals(a2):false
Arrays.equals(a1, a2):true
hash1 == hash2:false
Arrays.hashCode(a1) == Arrays.hashCode(a2):true
s1=[I@de6ced,s2=[I@c17164
_s1=[1,2,3,4,5],_s2=[1,2,3,4,5]
java.util.Arrays这个类提供了针对基本类型和对象类型的上述方法的所有版本,也提供了针对对象数组的deepXXX方法,有兴趣的 可以看一下。
下边是完整的源代码:
import java.util.Arrays;
/**
*
*/
public class Main {
/**Creates a new instance of Main */
public Main() {
}
private void test1() {
int[] a1 = {1,2,3,4,5};
int[] a2 = {1,2,3,4,5};
System.out.println("a1 == a2: " + (a1 == a2));
System.out.println("a1.equals(a2): " + (a1.equals(a2)));
System.out.println("Arrays.equals(a1,a2):" + Arrays.equals(a1,a2));
int hash1 = a1.hashCode();
int hash2 = a2.hashCode();
System.out.println("hash1 == hash2: "+(hash1 == hash2));
int_hash1 = Arrays.hashCode(a1);
int_hash2 = Arrays.hashCode(a2);
System.out.println("Arrays.hashCode(a1) == Arrays.hashCode(a2): "+(_hash1==_hash2));
String s1 = a1.toString();
String s2 = a2.toString();
System.out.println("s1=" + s1 + ",s2="+ s2);
String_s1 = Arrays.toString(a1);
String_s2 = Arrays.toString(a2);
System.out.println("_s1="+_s1+",_s2="+_s2);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Main main = new Main();
main.test1();
}
}