如何将整数转换为整数?

我的工作在一个网络应用程序,其中数据将传输之间的客户端和服务器端。

我已经知道 JavaScriptint! = Javaint。因为,Javaint 不能为 null,对吧。 这就是我现在面临的问题。

我把 Java int 变量改成了 Integer。

public void aouEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
Integer tempID = employee.getId();
String tname = employee.getName();
Integer tage = employee.getAge();
String tdept = employee.getDept();
PreparedStatement pstmt;
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/general";
java.sql.Connection con = DriverManager.getConnection(url,"root", "1234");
System.out.println("URL: " + url);
System.out.println("Connection: " + con);
pstmt = (PreparedStatement) con.prepareStatement("REPLACE INTO PERSON SET ID=?, NAME=?, AGE=?, DEPT=?");
pstmt.setInt(1, tempID);
pstmt.setString(2, tname);
pstmt.setInt(3, tage);
pstmt.setString(4, tdept);
pstmt.executeUpdate();
}

我的问题是:

pstmt.setInt(1, tempID);


pstmt.setInt(3, tage);

我不能在这里使用整数变量。我试过使用 intgerObject.intValue(); 但是它使事情变得更加复杂。我们还有其他的 < strong > 转换方法或转换技术吗?

任何补救措施都会更好。

331127 次浏览

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

Java converts Integer to int and back automatically (unless you are still with Java 1.4).

Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.

As already written elsewhere:

  • For Java 1.5 and later you don't need to do (almost) anything, it's done by the compiler.
  • For Java 1.4 and before, use Integer.intValue() to convert from Integer to int.

BUT as you wrote, an Integer can be null, so it's wise to check that before trying to convert to int (or risk getting a NullPointerException).

pstmt.setInt(1, (tempID != null ? tempID : 0));  // Java 1.5 or later

or

pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0));  // any version, no autoboxing

* using a default of zero, could also do nothing, show a warning or ...

I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.

Another simple way would be:

Integer i = new Integer("10");


if (i != null)
int ip = Integer.parseInt(i.toString());