== and equals are flawed in Java5


public class Test {
   public static void main(String[] args) {
      Long l1 = new Long(5);
      Long l2 = 5L;
      long l3 = 5L;
      int i1 = 5;
      // False, because l1 and l2 are different instances.
      System.out.println(l1 == l2); 

      // These two statements print true, because l3 is primitive
      // type. primitive types are compared in terms of value 
      // even if it is compared with == operator.
      System.out.println(l1 == l3);
      System.out.println(l2 == l3);
      // These three lines print true, because i1 is primitive. 
      // In the case of primitive and '==' operator, 
      // the contents of the variables, i.e., 5, are compared.
      System.out.println(l1 == i1);
      System.out.println(l2 == i1);
      System.out.println(l3 == i1); 
      // True      

      // False, because Integer and Long are different Class.
      // Compile error, because long and int are different types.
      // System.out.println(l3.equals(i1));

물론 원리 원칙에 맞게 한 것이지만, 제대로 코딩하기는 너무 어렵다는 점.

Similar Posts:

Trackbacks & Pingbacks 1

  1. From Younghoe.Info :: on 30 Nov -0001 at 12:00 am

    links from Technorati 편리한 것이라고 알고 있었지만… 차츰 부작용이 보고 되고 있다. 레거시1 를 보다 OO스럽게 포장하려던 계획은 그다지 우아하게 구현되지 못한 듯 하다. 0의 불일치 == and equals are flawed in Java5

Post a Comment

Your email is never published nor shared.