0

I'm doing this in my java file:

ArrayList<String> Matrix[][] = new ArrayList[n][n];

even if it works, i get this warning:

Type safety: The expression of type ArrayList[][] needs unchecked conversion to conform to ArrayList[][]

What's the problem? Thank you.

SegFault
  • 1,520
  • 2
  • 19
  • 36

1 Answers1

0

You haven't initialised it with a generic type.

Using Java 7 you can use the diamond. With Java 6 and below you have to initialise it with String as the generic type.

If you want to create an arraylist holding a two-dimensional array you do this:

ArrayList<String[][]> matrix = new ArrayList<>();

EDIT: I think you're trying to create an array of arraylists? It's better to declare it like so:

ArrayList<String>[][] matrix = new ArrayList<String>[][]();
Someone
  • 531
  • 3
  • 12
  • 1
    That wouldn't even compile. – Rohit Jain Jan 29 '14 at 16:31
  • Only the third option, `ArrayList matrix = new ArrayList<>()` will compile. – michaelsnowden Jan 29 '14 at 16:41
  • @Someone I would suggest you to go through the answer in the duplicate question to understand what is going on. – Rohit Jain Jan 29 '14 at 16:43
  • @RohitJain It's compiling for me. Also it makes sense to me. The other methods attempt to use the c-style array around the `ArrayList`, whereas that method attempts to create a normal ArrayList that contains a c-style array of Strings. – michaelsnowden Jan 29 '14 at 16:46
  • This compiles and works as expected: ArrayList matrix3 = new ArrayList<>(); String[] stringArr1= {"one", "two", "three"}; String[] stringArr2= {"one", "two", "three"}; String[] stringArr3= {"one", "two", "three"}; String[][] string2dArr = {stringArr1, stringArr2, stringArr3}; matrix3.add(string2dArr); – michaelsnowden Jan 29 '14 at 16:48
  • Sorry for any confusion previously. I kept making edits realising I'd missed/misread something. Everything should compile now. – Someone Jan 29 '14 at 16:53
  • @doctordoder Sorry, I missed that it's an `ArrayList` of `String[][]`. That's why I deleted the comment. – Rohit Jain Jan 29 '14 at 17:06
  • @Someone Your last declaration would still not compile. You can't create an array of parameterized types. – Rohit Jain Jan 29 '14 at 17:07
  • I was wondering if that's why you deleted it. Anyway, I'd like to know if the option I pointed out is good practice. Do you think so? – michaelsnowden Jan 29 '14 at 17:14
  • @doctordoder Yeah that is ok. There is nothing wrong with that. Anyways, the issue is in the question itself. Having 3 dimensional structure itself asks for some refactoring. Although, it can't be avoided, then `List` is fine. – Rohit Jain Jan 29 '14 at 17:16
  • @doctordoder Although, one should really avoid mixing up arrays, and generic types. They don't go well together. Both apply type checking at different times, one at compile time, other at runtime. – Rohit Jain Jan 29 '14 at 17:18
  • how can i handle the dimension of the matrix in this way? (n) – SegFault Jan 29 '14 at 17:35