如何将Integer转换为int?

71 java integer

我正在开发一个Web应用程序,在该应用程序中,数据将在客户端和服务器端之间传输.

我已经知道JavaScript int!= Java int.因为,Java int不能为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();
 }
Run Code Online (Sandbox Code Playgroud)

我的问题在这里:

pstmt.setInt(1, tempID);

pstmt.setInt(3, tage);
Run Code Online (Sandbox Code Playgroud)

我不能在这里使用Integer变量.我试过intgerObject.intValue(); 但它让事情变得更复杂.我们还有其他转换方法或转换技术吗?

任何修复都会更好.

use*_*421 69

正如其他地方所写:

  • 对于Java 1.5及更高版本,您不需要(几乎)执行任何操作,它由编译器完成.
  • 对于Java 1.4及更早版本,使用Integer.intValue()从Integer转换为int.

但是在你写的时候,一个Integer可以为null,所以在尝试转换为int(或冒险获得a NullPointerException)之前检查它是明智的.

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

要么

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

* 使用默认值零,也可以什么也不做,显示警告或...

我大多不喜欢不使用自动装箱(第二个样品线)所以我很清楚我想做什么.


Col*_*inD 13

既然你说你使用的是Java 5,可以使用setIntInteger因autounboxing:pstmt.setInt(1, tempID)应该只是罚款.在早期版本的Java中,您必须.intValue()自己调用.

相反的作品,以及...指派intInteger将自动使int使用被autoboxed Integer.valueOf(int).


spb*_*fox 7

Java将Integer转换为int并自动返回(除非您仍然使用Java 1.4).

  • 如果`Integer`为'null`会发生什么? (7认同)
  • @sparkandshine-有点晚了,但是-null应该会导致`NullPointerException` (2认同)

Jim*_*ugh 5

即使您使用的是 Java 5 JDK,也许您将 IDE 的编译器设置设置为 Java 1.4 模式?否则我同意其他人已经提到的自动装箱/拆箱。


Par*_*hta 5

另一个简单的方法是:

Integer i = new Integer("10");

if (i != null)
    int ip = Integer.parseInt(i.toString());
Run Code Online (Sandbox Code Playgroud)