日期:2014-05-20  浏览次数:20789 次

一个简单的equals问题
我的一个javabean如下:
    public   class   SimpleBean{
                  private   Object   key   =   null;
                  public   void   setKey(Object   key)   {
                  this.key   =   key;
              }
              public   Object   getKey(){
                        return   key;
              }
    }
   
我给SimpleBean类Set一个值,
      SimpleBean     sb=     new   SimpleBean();
      sb.setKey( "test ");
     
我的一个List,然后添加一个值   list.add( "test ").

我现在比较内容         String   str1   =   sb.getKey.toString();
                                    String   str2   =   list.get(0).toString();
                                   
                        str1和str2的内容都是 "test ",为什么str1.equals(str2)返回false啊?

------解决方案--------------------
rpwt

import java.util.ArrayList;
import java.util.List;

public class SimpleBean
{
private Object key = null;

public void setKey(Object key)
{
this.key = key;
}

public Object getKey()
{
return key;
}

public static void main(String[] args)
{
SimpleBean sb= new SimpleBean();
sb.setKey( "test ");
List list = new ArrayList();
list.add( "test ");

String str1 = sb.getKey().toString();
String str2 = list.get(0).toString();

System.out.println(str1.equals(str2));
}
}


true
------解决方案--------------------
试试
str1.equals(str2.toString())

你写str2比的是对象。equals比的是内容