comparing arrays in java

后端 未结 6 1594
醉梦人生
醉梦人生 2020-12-03 12:58
int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;


int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;

boolean t = nir1.equals(nir2);
boolean m = nir1.toString         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 13:12

    I just wanted to point out the reason this is failing:

    arrays are not Objects, they are primitive types.

    When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().

    The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.

    Like suggested by other posters, the way to go is by using the Arrays class:

    Arrays.toString(nir1);
    

    and

    Arrays.deepToString(nir1);
    

    for complex arrays.

    Also, for equality:

    Arrays.equals(nir1,nir2);
    

提交回复
热议问题