添加到 map 时Java异常

标签 java dictionary nullpointerexception

不确定出了什么问题...它应该可以工作,或者可能缺少某些东西?代码如下:

public class TestOracleMap implements java.io.Serializable{
static TreeMap<String, Integer> map;
static TreeMap<String, Integer> localMap = new TreeMap<String, Integer>();

public static void StoreMapInDB(TreeMap<String, Integer> map) throws
        IOException, FileNotFoundException{
    try {
  PreparedStatement insertMap = null;
  //String insertString = "INSERT INTO TESTMAP(ID, MPFIELD) VALUES (1, ?)";
  Connection con=null;
  con.setAutoCommit(false);
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con=DriverManager.getConnection(
    "jdbc:oracle:thin:@oXXX",
    "XXX",
    "XXX");

  ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
  ObjectOutputStream out = new ObjectOutputStream(bos);
  out = new ObjectOutputStream(bos) ;
  out.writeObject(map);
  out.close();

  byte[] buf = bos.toByteArray();
  PreparedStatement prepareStatement = con.prepareStatement("insert into  

  TESTMAP(ID,MAPFIELD)values(?,?)");
  prepareStatement.setLong(1, 1);
  prepareStatement.setBinaryStream(2, new ByteArrayInputStream(buf), buf.length);



 // insertMap.executeUpdate();
  con.commit();
    } catch(Exception e){e.printStackTrace();}
}

public static void main(String[] args)
{
    try{
    DateTime today = new DateTime();
    int x = 1;
    map.put("Hello!", x);
    StoreMapInDB(map);
    }catch(IOException ioe){
        System.err.print(ioe);
    }
}
}

错误出现在 main 方法中的行中,即:

map.put("Hello!", x);

它给出:

Exception in thread "main" java.lang.NullPointerException
at core.smd.classes.TestOracleMap.main(TestOracleMap.java:61)
 Java Result: 1

最佳答案

似乎您从未实例化map。您在这里声明

static TreeMap<String, Integer> map;

但是当你在这里使用它时,它仍然是null,给你NullPointerException

map.put("Hello!", x);

如果您之前这样做过

map = new TreeMap<String, Integer>();

它应该运行良好。

关于添加到 map 时Java异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8413544/

相关文章:

java - 奇怪的空指针异常

Java 代码 - NullPointerException

java - Struts2从JSP发送列表数据到Action类: alternative way

python - 如何迭代和修改字典中的值?

以列表作为值的 Python 字典到 Pandas 数据框

ios - 如何动态添加swift字典中的值

java - 什么是NullPointerException,我该如何解决?

java - 什么时候可以捕获NullPointerException?

java - 如果 REST Controller 类和接口(interface)具有使用 @HystrixCommand 注释的 API,则不会加载所有 REST API

Java Swing、 boolean 值和文本字段