n1==n2和n1 != n2比较的是两个对象的实际地址
你想要的效果应该是调用方法equals

解决方案 »

  1.   

    public class Equivalence{
              public static void main(String[] args){
                Integer n1=new Integer(47);
                Integer n2=nwe Integer(47);
                System.out.println(n1==n2);
                System.out.println(n1!=n2);
              }
             }
    为啥比较结果是 true和false 但实际答案是现是false 再是true。我这样理解2个Integer的对象都相同为啥会出现不同结果。
    楼主,你到底认为应该是什么答案呢?
    你运行的结果又是什么答案呢?n1和n2都是对象
    == 操作符,对于对象来说,只比较对象的引用,即指针的地址值,对于两个不同的对象来说,当然是不相等的另外第二段函数应该结果是false
      

  2.   

    先是false后是true是正确的。除了基本类型,int, char, byte等,所有的类型都是实际上都是一个reference,类似于c++的指针,所以你这样毕竟其实是毕竟两个对象的指针,肯定就是后一种结果。
    所以比较Interger的实际值47,就要用equals, 如果你要实现的类需要做比较,则你的类要实现(overload,重载)equals方法。
      

  3.   

    我运行的结果 先是flase 然后是true想知道引用和对象的区别!n1和n2都是对象
    == 操作符,对于对象来说,只比较对象的引用,即指针的地址值,对于两个不同的对象来说,当然是不相等的
    这句话还是不是很理解        对象的引用难道就是对象的所指的值吗?
      

  4.   

    public class B
    {
      public static void main(String args[])
      {
        int a=10;
        System.out.println("a="+a);
        int b=a/2;
        System.out.println("a="+a);
        
        StringBuffer sa=new StringBuffer("sa");
        System.out.println("sa="+sa);
        sa.append("append");
        System.out.println("sa="+sa);
        }
     }体会一下吧,你就知道java中的引用是怎么回事了
      

  5.   

    看这段代码:
     class Value{
              int i;
                      }
     public class Equivalence{
         public static void main(String[] args){
                 Value v1=new Value();
                 Value v2=new Value();
                 v1.i=v2.i=100;
             System.out.println(v1.equals(v2));//第九行
             System.out.println(v1==v2);//第十行
             }
       }
    执行结果是:false、false
    首先你要知道:“==”比较的是引用,你可以把他理解为地址的比较;equals比较的是对象。好了,现在看上面的程序,第十行输出肯定是false,因为v1和v2两个对象的地址不可能相等,那么第九行为什么也是false呢,他不是比较对象v1和v2吗?这就涉及到深比较和浅比较的问题了,没错,v1.i==v2.i,那又能代表什么,那只不过是v1和v2深层次的某个成员变量的值相等罢了。象string类型的equals函数是通过重载object的equals函数的,他应当别论,在java中有许多这样的类型重载equals函数。如果你非要第九行输出结果为true,那么你重载equals函数,让他深入到value的更深层去比较。
      

  6.   

    ==      比较的是内存的物理地址
    equals  比较的是内容,区分大小写
      

  7.   

    equals
        public boolean equals(Object obj)Determines whether or not two points are equal. Two instances of Point2D are equal if the values of their x and y member fields, representing their position in the coordinate space, are the same. Overrides:
        equals in class Point2D
    Parameters:
        obj - an object to be compared with this Point2D 
    Returns:
        true if the object to be compared is an instance of Point2D and has the same values; false otherwise.