• Post Reply Bookmark Topic Watch Topic
  • New Topic

Best way to create a matrix  RSS feed

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
I am writing a Matrix class. Is a 2-D array the best way to represent a Matrix internally in the Matrix class?
I think it is the most intuitive way to supply data for the creation of a matrix. What are the advantages and disadvantages of representing it as a
collection of a collection?
Thanks.
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main advantage is that Collections can be dynamically resized easily (just add a new member). The main disadvantage is there will be a performance hit, which can be significant if you use the wrong Collection or wrong methods to access the members. Another disadvantage is that primitives must be wrapped since all the access methods of collections use as parameters and return Objects, so if you have a Matrix of doubles, then you would have to wrap them all in Doubles and change them back when retrieved, which causes another slight perfomace hit.
 
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The new JDK (1.5) has a couple of features that might mitigate some of the overhead Michael mentioned. You get "autoboxing", which means that you can add primitives directly to collections and the JVM will autowrap them for you. Also, you can define collections of specific types, so you don't have to explicitly cast objects when you retrieve them later. I realize that this is only in beta form and most people won't be using this in production for a while.
Meanwhile, the answer to your original question might depend on how you use the matrix. Some applications do most of the matrix building up front, and then simply read the data after that.
If your application follows that model, then my suggestion is for you to initially define it as a collection of collections so you don't have to worry about constantly resize it. Once it's built then convert it to an array of arrays and access it that way. You get the best of both worlds.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I wrote my own Matrix class a while ago, I opted to use a 2D array, primarily for the reasons already given. I decided that the constructor would take the size as parameters, so it wouldn't change once it was created.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!