Reputation: 1123
I am trying to do the following code:
public class AddressManager
{
private ArrayList<Address>[] array;
private int depth;
public AddressManager(int d, int s, Address a)
{
array = new ArrayList<Address>[d];
}
}
There is more to my code, but this amount of code is sufficient to show my problem. Of course, netbeans shows a compile error to do with generic arrays, on the line with "new ArrayList...", and i have read up alot about this.
There are explainations all over the web stating things about the compiler not being able to verify types in assignments if you do this, and lots of questions about this are right here on StackOverflow! There are also supposedly ways to work around this, so long as you show the compiler that "You know what you're doing!". The issue is that i can't get this to work, i can't understand the explanations, and i really do want an array of arraylists.
Could someone please explain in more simple language what i can do to get around this error in my specific case? I have tried the following sort of idea:
private Object[] array;
array = (ArrayList<Address>[]) new Object[d];
But it seems it can not be cast correctly, even though one of the sites i saw said you could do something like this, or use "@SuppressWarnings("unchecked")" with something or other. Please, i need this in a way that is more clear than examples that don't quite match my situation like This solution, which works great for maps, but not ArrayLists.
The other answers to questions just like mine on StackOverflow may be very helpful indeed, but i do not understand them very well, or i would not be writing this request for something more down to earth.
Upvotes: 3
Views: 173
Reputation: 760
There is nothing wrong with the following:
@SuppressWarnings("unchecked")
ArrayList<Address>[] array = (ArrayList<Address>[]) new ArrayList<?>[d];
You just need to be sure that you really are only storing ArrayList<Address>
in the array. If you are sure of that, then you can safely suppress the warning. There's nothing wrong with using generic arrays in principle. The compiler is just protecting you from doing something like this accidentally.
Upvotes: 3