我们知道,Java对于基础类型和引用类型分的很清晰,如数组、集合等是很常见的引用类型,下面有个案例是将map作为形参,然后在新的方法里对其进行修改:
运行时却报错:
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at com.jwb.neo4j.QueryKnowledge.replaceMapOfName(QueryKnowledge.java:94)
at com.jwb.neo4j.QueryKnowledge.querySingleEntry(QueryKnowledge.java:31)
at com.jwb.neo4j.QueryKnowledgeTest.test_querySingleEntry1(QueryKnowledgeTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
理论上来说,map作为形参传递是一个对象的引用,而在新的方法里对其进行修改,改的实际上是内存中那个对象,所以调了这个replaceMapOfName方法,会其原来map进行了修改,但是为什么会抛出异常呢?
分析:
1)debug,运行到 map.put("名称", name); 就抛出异常,也就是说一修改就会报错
2)假设1:是因为 这个map对象放入形参,仅仅是一个拷贝的内存对象副本,而这个副本是只读的,不能对其修改?
3)假设2:由于Map本身就是一个接口,里面的add方法是抽象方法并没有实现,而这里面作为形参
4)假设3:这个对象被改为了 不可修改的map(juc包下的)
最后验证第三个假设时,找到原因了
这样就解决了问题