如何在Java中比较字符串和对象

时间:2012-06-23 15:47:23

标签: java

我将此代码剪断,用于输入验证:

public void validaUserID(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException {

        int findAccount = 0;

        if (ds == null) {
            throw new SQLException("Can't get data source");
        }
        // Initialize a connection to Oracle
        Connection conn = ds.getConnection();

        if (conn == null) {
            throw new SQLException("Can't get database connection");
        }

        // Convert Object into String
        int findValue = Integer.parseInt(value.toString()); 

        // With SQL statement get all settings and values
        PreparedStatement ps = conn.prepareStatement("SELECT * from USERS where USERID = ?");
        ps.setInt(1, findValue);
        try {
            //get data from database        
            ResultSet result = ps.executeQuery();
            while (result.next()) {
                // Put the the data from Oracle into Hash Map
                findAccount = result.getInt("USERID");
            }
        } finally {
            ps.close();
            conn.close();
        }

        // Compare the value from the user input and the Oracle data
        if (value.equals(findAccount)) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    value + " Session ID is already in use!", null));
        }
    }

由于某种原因,输入数据未与Oracle中的值正确比较。比较这两个值的正确方法是什么?

3 个答案:

答案 0 :(得分:6)

看起来你正在比较盒装整数。我打开它们(即以原始形式获取它们)并执行==而不是.equals

答案 1 :(得分:1)

Objects are compared using .equals()and String is an object too, so they also have to be compared using .equals().

例如:

假设s1和s2为String。

s1.equals(S2);

Primitive variables are compared using == 因为包装器是对象,您需要将它们与.equals()but if you want to compare them using ==进行比较那么你必须先将它们转换成它的原始形式。

例如:

整数a = 5;

int i = new Integer(a);

答案 2 :(得分:1)

好。答案在于你的代码本身。

 if (value.equals(findAccount)) 

你可以这样写它

  if (findValue == findAccount)) 

因为您已经将对象解包为原始 findValue

更清楚的是,调用equals()并仅传递给对象。您无法将对象与基元进行比较,反之亦然。