제 생각과 다른 결과가 나와서 설명좀 부탁드립니다.
남자
public class testequals {
public static void main(string[] args) {
int[] a = new int[3];
int[] b = new int[3];
int i;
for (i = 0; i a.length; i++)
a[i] = i;
for (i = 0; i b.length; i++)
b[i] = i;
if (a == b)
system.out.println(equal by ==.);
else
system.out.println(not equal by ==.);
if (equals(a, b))
system.out.println(equal by the equals method.);
else
system.out.println(not equal by the equals method.);
}
public static boolean equals(int[] a, int[] b) {
boolean match;
if (a.length != b.length)
match = false;
else {
match = true;
int i = 0;
while (match && (i a.length)) {
if (a[i] != b[i])
match = false;
i++;
}
}
return match;
}
}
실행결과입니다.
not equal by ==.
equal by the equals method.
제가 자바를 처음으로 공부하는거라 아직 개념도 제대로 안서고 잘 모릅니다.
a,b모두 같은 length로 선언이 되었고, length보다 작을동안 1씩 더하므로
equal by ==가 나와야 될것 같은데 실행 결과가 아래와같이 나옵니다.
not equal by ==.
equal by the equals method.
if, for, 변수선언, array선언은 대충 이해했습니다.
그런데 왜 저런 결과가 나오는지 잘 모르겠습니다. 머리가 나쁜지라 ㅡㅡ;;;
실행결과가 왜 저렇게 나오는지 설명좀 부탁드립겠습니다.
-
보단
System.out.println(a);
System.out.println(b);
하면 이상한 문자가 나올껍니다
==로 비교하면 이 문자를 비교하게 됩니다
이 문자는 a,b의 메모리 상의 주소라고 생각하시면 됩니다
a,b는 따로 만들어졌기 때문에 다르다고 나옵니다
반면에 equals는만든 함수이죠?
배열 a, b의 요소 하나씩을 꺼내서 비교하였기 때문에 숫자끼리 비교가 된 것 입니다.