我在 Android 设备上运行了这个 Scala 代码:
// create Map
val myMap1 = new HashMap[Int, String]()
myMap1.put(1, "a")
// write it to file
val outStream = context.openFileOutput("test.txt", Context.MODE_PRIVATE)
val ostream = new ObjectOutputStream(outStream)
ostream.writeObject(myMap1)
ostream.close
// read from file
val inStream = context.openFileInput("test.txt")
val istream = new ObjectInputStream(inStream)
val myMap2 = (istream.readObject).asInstanceOf[HashMap[Int, String]]
istream.close
// java.lang.NullPointerException accessing myMap2
if (myMap2.contains(1)) { println("yes") } else { println("no") }
我创建一个 mutable.HashMap 并将其写入文件,读取它,然后 HashMap 为空。为什么是myMap2
null 并且没有任何内容?下面是调试会话的屏幕截图。
完整的堆栈跟踪:
java.lang.NullPointerException
at scala.collection.mutable.HashTable$class.index(HashTable.scala:353)
at scala.collection.mutable.HashMap.index(HashMap.scala:39)
at scala.collection.mutable.HashTable$class.findEntry(HashTable.scala:130)
at scala.collection.mutable.HashMap.findEntry(HashMap.scala:39)
at scala.collection.mutable.HashMap.contains(HashMap.scala:60)
at com.test.mytest.bean.MyItem$.read(MyItem.scala:74)
at com.test.mytest.bean.MyItem$.add(MyItem.scala:93)
at com.test.mytest.frag.MyFragment.onClick(MyFragment.scala:114)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)