== -> 레퍼런스 비교
equals -> 문자열 비교
instanceof -> 객체비교
class Test
{
int value;
public Test(int value)
{
this.value = value;
}
}
class EqualsTest
{
public static void main( String [] args )
{
Test t1 = new Test(10);
Test t2 = new Test(10);
if(t1.equals(t2)) //객체의 주소값을 비교
{
System.out.println("t1과 t2는 같습니다.");
}else
{
System.out.println("t1과 t2는 다릅니다.");
}
System.out.println(t1);
System.out.println(t2);
t2 = t1;
if(t1.equals(t2)) //문자열 비교
{
System.out.println("t1과 t2는 같습니다.");
}else
{
System.out.println("t1과 t2는 다릅니다.");
}
System.out.println(t1);
System.out.println(t2);
}// end main
}
Test t1 = new String("new"); ==> new 가 출력
Test t2 = new Test(10); ==> t2 객체의 주소값을 출력
String 클래스 객체는 객체의 주소값을 갖는게 아니라 문자열 자체를 갖는다.
왜냐면.. 자주 쓰기때문에 편의를 위해서 자바 자체적으로 요로케 만들어 놨음.
1 . String aa ="aaa";
2 . String aa = new String("aaa"); 둘중에 뭐가 편한가?
class Car
{
int velocity; //속도를 정수형으로
int wheelNum; // 바퀴수를 정수형으로
String carName; // 차의 이름을 String클래스로 선언
public Car(int speed, String name, int wheel)
{
velocity = speed;
carName = name;
wheelNum = wheel;
}
public boolean equals(Object ob) //문자열 비교
{
Car c = (Car)ob;
if((carName == c.carName) && (wheelNum == c.wheelNum) && (velocity == c.velocity))
{
return true;
}else
{
return false;
}
}
public String toString() //오버라이딩
{
String s = "이 차는 "+carName+"이고 바퀴가 " + wheelNum +"개이고 ,현재 속도는 "+ velocity;
return s;
}
public static void main( String [] args )
{
Car c1,c2;
c1 = new Car(100,"소나타",4);
c2 = new Car(100,"소나타",4);
System.out.println(c1.toString());
System.out.println(c2.toString());
if(c1 == c2) //객체 주소값 비교
{
System.out.println("레퍼런스 같음");
}else
{
System.out.println("레퍼런스가 틀림");
}
if(c1.equals(c2)) //String 클래스의 문자열 객체는 주소값이 갖는게 아니라 문자열 자체를 같는다.. 자바특성..
// 그래서 문자열 비교를 하게된다. 하지만 이 예제는 equals가 오버라이딩 되어있다...
{
System.out.println("객체의 내용이 같네요");
}else
{
System.out.println("겍체의 내용이 틀리네요");
}
}// end main
}