Java: Array of List<MyClass>

末鹿安然 提交于 2020-01-30 13:15:28

问题


I have a spec that requires me to pass an array of lists. The array is always length 2. I am using the following to accomplish this:

List<MyClass> [] data = new ArrayList[2];
data[0] = new ArrayList<MyClass>();
data[1] = new ArrayList<MyClass>();

compiles but gives warning:

uses unchecked or unsafe operations.

I understand that Arrays of generics are not allowed in Java however I cannot change the spec and the above code seems to work nicely. As long as I am conscious that I never reassign the elements of the array to be something other than type ArrayList<MyClass> are there any reasons I should not just suppress this warning and be on my way?


回答1:


The compiler in your case, warning you that your code isn't going to do any checking for you that which type of values you are adding to your array. You can ignore this warning, as long as you are ensuring that only ArrayList<MyClass> type are added to your array.

@SuppressWarnings("unchecked") is present for a reason in java, you can suppress the warning and let your compiler know that you don't need it's type checking.




回答2:


You cannot create Generic Arrays; see the official Java documentation on the subject.

You can still get rid of the compile-time warning, like so...

List[] data = new List[2];

Of course, this means that you need to check the type of everything going in to/coming out of the Lists when you start referencing their data & casting it appropriately. So be wary.




回答3:


It's OK to suppress the warning given that Java doesn't allow generic array creation. Although it is no safe, there is no other way to create arrays with generics unless you ignore or suppress that warning.



来源:https://stackoverflow.com/questions/41558687/java-array-of-listmyclass

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