Re: Adding custom element to ArrayList
On 3/15/2011 10:41 PM, D R wrote:
I created a class called matrix to perform some work on a 2D array,
which I implemented with:
int array[][];
Now I'm trying to modify it to handle sparse arrays. I'm using an
array of ArrayLists like so:
private ArrayList<Element>[] rows;
//and in the matrix constructor...
rows = new ArrayList [nRows];
for (int i=0; i<nRows; i++){
rows[i] = new ArrayList<Element>();
and the Element class looks like this:
class Element {
private int column;
private int value;
//Element constructor
public Element(int column, int value){
this.column = column;
this.value = value;
}//close Rows constructor
Side-note: Comments that state the obvious are useless. Those
that state falsehoods are less than useless.
public int getColumn(){
return column;
}
public int getValue(){
return value;
}
I have a setElement method that used to take (int row, int column, int
value) when it was a 2D array (array[row][col]=value;) but I've
changed it to:
public void setElement(int row, Element e) {
rows[row].add(e); }
One difficulty is that an ArrayList is not sparse; another is
that an ArrayList can contain duplicate elements. So, if you set
elements 10<-5, 20<-6, 10<-7 in succession, you'll get lists that
we might represent as
(10,5)
(10,5) (20,6)
(10,5) (20,6) (10,7)
You could still make this work (by searching linearly through the
list for the Element you want, working backwards so as to pick up
the most recently-set version), but it would be horribly slow.
Now I'm trying to add (column,value) Elements to my rows ArrayList but
I must be using the wrong syntax.
I'm trying:
setElement(r2, c2, getElement(r1, c1));
where r2 is an int representing row, c2 is an int representing column
and getElement(r1,c1) returns an int value.
I'm getting an error that says "the setElement method cannot be
applied cannot be applied to given types. required: int,
Matrix.Element
found: int, int, int
Question #1: How many parameters does the setElement method take,
and of what types?
Question #2: How many arguments does the call offer, and of what
types?
Question #3 (essay): Discuss.
Any suggestions are greatly appreciated.
One easy-to-implement approach would be to have a class called
Coordinates or Indices or some such, carrying the row/column position
and implementing the hashCode() and equals() methods. Then you could
represent the matrix as a HashMap<Coordinate,Integer>. It's by no
means an "industrial-strength" solution and will be very slow, but
it won't be as slow as the approach you're now following.
--
Eric Sosman
esosman@ieee-dot-org.invalid