• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

manipulation of 2d array

 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, that's right! Didn't even think of that! Thank you!
 
Marshal
Posts: 80775
489
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic