Java: Array of List<MyClass>

222 views Asked by At

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?

3

There are 3 answers

0
Amit Bhati On BEST ANSWER

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.

3
alayor On

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.

0
nasukkin On

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.