开发者

Java implementing clone, generic class.

开发者 https://www.devze.com 2022-12-19 22:32 出处:网络
I have a class that implements a 2Dtable. The elements in the table is generic. And the table is stored like this:

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 th开发者_Go百科e 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; 
    }


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号