== 연산자
- int, boolean과 같은 Primitive type에 대해서 값 비교
- Reference type에 대해서는 주소값 비교
- Primitive type도 Constant Pool에 있는 특정 상수를 참조하는 것이기 때문에 결국 주소값을 비교하는 것으로 볼 수 있음
int a = 10;
int b = 10;
int c = 20;
System.out.println(a==b); //true
System.out.println(a==c); //false
변수 a,b,c는 값이 stack에 존재하므로 stack에 있는 변수 값만 비교하게 됨
equels()
- Object에 포함되어 있기 때문에 equals()를 재정의 해서 사용할 수 있음
Object의 equals()
public boolean equals(Object obj)
{
return (this == obj);
}
String의 equals()
public boolean equals(Object anObject()
{
if (this == anObject)
{
return true;
}
if (anObject instanceof String)
{
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length)
{
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while ( n-- != 0 )
{
if ( v1[i] != v2[i] )
return false;
i++;
}
return true;
}
}
return false;
}
- 주소값 비교해서 같으면 if (this == anObject) true 리턴
- 주소값이 다르면 char 타입으로 하나씩 비교해보면서 같다면 true, 다르면 false 리턴
==는 주소값 비교, equals()도 내부적으로는 주소값을 비교하지만 String 클래스에서는 재정의가 되어 있어 내용 또한 비교하게 되어 있음
'JAVA' 카테고리의 다른 글
Java의 데이터 타입 (0) | 2023.05.31 |
---|---|
자바의 Math (0) | 2023.05.29 |
자바에서 final이란? (0) | 2023.05.28 |
두 객체가 동일한 HashCode를 가지면? (0) | 2023.05.27 |
JDK 와 JRE의 차이점 (0) | 2023.05.25 |