Why auto-boxing marked as a warning?

别来无恙 提交于 2019-12-05 14:20:00

问题


I understand that auto un-boxing should be done with care because the reference that is being un-boxed can be null. Why is auto-boxing marked as warning as well? Are there some pitfalls I am missing here?


回答1:


If you don't expect performance issues (in terms of micro-optimization) you can safely disable this warning. It is just an indication in case you're not aware that auto-boxing happends here. In business-logic code where you have I/O overhead (due to DB transactions or disc access) auto-boxing hardly becomes a performance issue.




回答2:


I was going to disable this Eclipse warning but the following article made me consider not to. I'm still not completely sure but it looks to me like those might be good reasons to just avoid autoboxing.

https://effective-java.com/2010/05/the-advantages-and-traps-of-autoboxing/




回答3:


Autoboxing can contribute to the developer creating a bug related to the "remove" method of Collections, though this is probably a pretty obscure bug.

I've encountered this bug when I used a random number generator to select the index of an item to remove from an ArrayList. The generator returned a long primitive, which I accidentally tried to use as the parameter for List.remove(int index). The compiler converted the long to a Long and used it in List.remove(Object o), which gave totally different behavior. Luckily, an assert statement caught the error quickly.

According to this discussion of this issue with "remove", someone else ran into a similar problem where their int unexpectedly acted like an Integer, though I don't understand how that happened. Why aren't Java Collections remove methods generic? (see comment by ScArcher2)



来源:https://stackoverflow.com/questions/8248092/why-auto-boxing-marked-as-a-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!