• Post Reply Bookmark Topic Watch Topic
  • New Topic

manipulation of 2d array  RSS feed

 
liliya woland
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I want to get the code below to run, but at this point Collections.sort(c) throws java.lang.ClassCastException.
Basically, I want to get a max or max by index from a 2d array. I have it working when I do manual 2d array traversal, but I'm hoping to make something faster. Any relevant input is much appreciated.
Here is what I have:

 
Tony Docherty
Bartender
Posts: 3268
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In future, if you get an exception please include the full exception message and stack trace in your post.

The addAll() method won't add every int value in the 2D array to the ArrayList, it will add each of the 1D arrays that make up the 2D array and as int arrays do not implement Comparable the sort fails.
I have noticed you haven't used generics when declaring your ArrayList, if you had the code would have failed to compile - a good reason to use generics.

If you want to add all the int values use a for-each loop to iterate over the first dimension of matrix and add each returned 1D array to the collection.
 
liliya woland
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, that's right! Didn't even think of that! Thank you!
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What’s a 2D array? Java doesn’t support them. It supports arrays of arrays, which are better than 2D arrays.
 
Tony Docherty
Bartender
Posts: 3268
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What’s a 2D array? Java doesn’t support them.

Fair point, I stand corrected.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!