views:

167

answers:

2

I have a class that implements a 2Dtable. The elements in the table is generic. And the table is stored like this:

public Object[][] list;

The problem is that calling clone on this apparently doesn't work. Note that my testcase initializes the table to store normal Integers.

Tabell2D<Integer> en = new Tabell2D<Integer>(5,5);
        en.sett(0, 0, 55);
        Tabell2D<Integer> to = en.clone();
        to.sett(0, 0, 11);
        assertTrue(en.equals(to)); 

Here I make a table. Change it, clone it. Change the clone, and compare them. Obviously the clone is changed. Even so, this assertTrue is well true.

The equal method is generated by eclipse:

public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Tabell2D other = (Tabell2D) obj;
        if (bredde == null) {
            if (other.bredde != null)
                return false;
        } else if (!bredde.equals(other.bredde))
            return false;
        if (høyde == null) {
            if (other.høyde != null)
                return false;
        } else if (!høyde.equals(other.høyde))
            return false;
        if (!Arrays.equals(liste, other.liste))
            return false;
        return true;
    }

I assume that the problem is either in the compare of the list variable in equal, or the problem is in the clone method. Clone method:

public Tabell2D<E> clone(){
        Tabell2D<E> nyTab = new Tabell2D<E>(this.bredde,this.bredde);
        nyTab.liste = liste.clone(); 
        return nyTab; 
    }
A: 

Clone is supposed to return Object. Your "clone" isn't overriding the normal one.

Also, I don't know that cloning an array does a deep copy. You'd probably be better off to create a new array and assign the elements.

Paul Tomblin
So my professor would be an ... for including this: public abstract ITabell2D<E> clone();in the Tabell2D interface?
Algific
He should call it something else.
Paul Tomblin
professor? I don't get it.
bmargulies
teacher?.........
Algific
Since Java 1.5 an overriding method may specialize the return type, i.e. `Foo clone()` can override `Object clone()`. This is called a *covariant return type*. That is, the answer's first sentence is incorrect for recent versions of Java.
meriton
@misterfixit: Making a shallow copy of an array isn't necessarily wrong. It just depends what you're trying to accomplish. So I'd hesitate before ridiculing your professor.
Jay
+2  A: 

I think that the root of the problem is that cloning a 2d array doesn't go deep. If you want a deep copy of 'liste' you need to write your own code to copy each row (or column depending on how you look at it).

bmargulies
I'll try it, thanks!
Algific
This worked! Manually transferring each element in the table. And I also needed a custom equal method, the one eclipse generates did not work out.
Algific