Как установить Deep copy в конструкторе копирования?

1

Мне нужно, чтобы мой конструктор копий был глубоко скопирован в моем классе и сегменте, но я не уверен, правильно ли я это сделал или нет. Может ли кто-нибудь помочь?

public class Segment implements SegmentInterface {
    // two Points that hold endpoints of the segment
    private Point p1;
    private Point p2;

    // Default constructor that will set the endpoints to new
    // Points with values (0,0) and (4,4)
    public Segment() {
        //this(0, 0, 4, 4);
        this.p1 = new Point(0, 0);
        this.p2 = new Point(4, 4);
    }

    // Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
    // and creates and sets the endpoints
    public Segment(int x1, int y1, int x2, int y2) {

        //this.p1 = new Point(x1, y1);
        //this.p2 = new Point(x2, y2);

        if(x1 != x2 && y1 != y2){
            this.p1 = new Point(x1, y1);
            this.p2 = new Point(x2, y2);
        } 

        else{
        throw new IllegalArgumentException("undefined");
    }
}

    // Parameterized constructor that accepts (Point p1, Point p2) and sets both
    // the endpoints to a deep copy of the Points that are passed in.

    public Segment(Point p1, Point p2) {

        if(p1 != p2){
        this.p1 = new Point(p1.getX(), p1.getY());
        this.p2 = new Point(p2.getX(), p2.getY());
        }       
            else{
                throw new IllegalArgumentException("Points cannot have same values!");
            } 
}

    // Copy constructor that accepts a Segment and initializes the data (of the
    // new Segment being created) to be the same as the Segment that was
    // received.
    public Segment(Segment other) {

            this.p1 = other.p1;
            this.p2 = other.p2;
}

Пожалуйста, подумайте, что это не весь код!

Класс My Point:

public class Point implements PointInterface {

    // hold the x-value and the y-value of the Point
    private int x;
    private int y;

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    // default constructor that will set the values to (0, 0)
    public Point() {
        this.x = 0;
        this.y = 0;
    }

    // parameterized constructor that will receive 2 ints (first the x
    // coordinate and then the y)
    // and set the data variables to the values received.
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // A copy constructor that will receive a Point and then initializes the
    // data
    // Deep Copy
    public Point(Point other) {
        this.x = other.getX();
        this.y = other.getY();
    }
  • 3
    Примечание. Если вы сделаете свой класс Point неизменяемым, вам не понадобится глубокое копирование ...
  • 2
    В Java нет конструкторов копирования. Вы можете написать что-то подобное сами, но то, что это делает, полностью зависит от вас. Компилятор не заботится о них и не имеет для них дополнительных «настроек». Я полностью согласен с @OliverCharlesworth. Вам не нужно делать это. Мне никогда не приходилось писать «конструктор копирования» или использовать clone() в Java за 17 лет.
Показать ещё 3 комментария
Теги:
deep-copy

1 ответ

0

Почти хорошо. Используйте этот конструктор для сегмента:

public Segment(Segment orig)
{
    this(orig.p1, orig.p2);
}
  • 0
    А? У него это уже есть.
  • 0
    @ EJP: Нет, не проверяйте внимательно.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню