== and equals are flawed in Java5

Tags:

http://www.coconut-palm-software.com/the_visual_editor/?p=88

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      
      System.out.println(l1.equals(l2)); 
      System.out.println(l1.equals(l3)); 
      System.out.println(l2.equals(l3)); 

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

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

Comments

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

Leave a Reply

Your email address will not be published. Required fields are marked *