0

我正在尝试使用复制构造函数复制对象,但它输出错误:

Exception in thread "main" java.lang.NullPointerException
at Polynomial.<init>(Polynomial.java:30)
at Polynomial.showDerivative(Polynomial.java:59)
at Program.main(Program.java:9)

这是我的复制构造函数:

public Polynomial(Polynomial poly)
{
    for(int i = 0; i < a.length; i++)
        a[i] = poly.a[i];
    for(int i = 0; i < b.length; i++)
        b[i] = poly.b[i];
}

这就是我实例化对象的方式:

Polynomial pol = new Polynomial(this);

我该怎么办?

谢谢。

4

3 回答 3

1

System.arraycopy使用创建数组的副本会更好。

此外,将您的复制构造函数更改为: -

public Polynomial(Polynomial poly)
{
    int aLen = poly.a.length;
    int bLen = poly.b.length;

    // Initialize arrays for this object
    a = new int[aLen];  // Assuming `a` and `b` are integer arrays
    b = new int[bLen];  // Change accordingly.

    // A better way to create copy of arrays would be to use `System.arraycopy
    System.arraycopy( poly.a, 0, a, 0, aLen);
    System.arraycopy( poly.b, 0, b, 0, bLen);


    /*** You can avoid using below loops ***/

    // Iterate till the `aLen` of `poly` object passed 
    // and add elements to `a` array of this object
    /*for(int i = 0; i < aLen; i++)
        a[i] = poly.a[i];

    // Iterate till the `bLen` of `poly` object passed 
    // and add elements to `b` array of this object
    for(int i = 0; i < bLen; i++)
        b[i] = poly.b[i]; */
}

您的for循环应该运行到poly.aandpoly.b和 not aand的长度b,因为它们尚未初始化,因此NPE.

于 2013-01-22T19:00:52.793 回答
0

假设您的Polynomial课程如下所示:

public class Polynomial {

    private int[] a;
    private int[] b;

    public Polynomial(int length) {
        a = new int[length];
        b = new int[length];
    }

    public Polynomial(Polynomial poly)
    {
        for(int i = 0; i < a.length; i++)
            a[i] = poly.a[i];
        for(int i = 0; i < b.length; i++)
            b[i] = poly.b[i];
    }


    public static void main(String[] args) {
        Polynomial p = new Polynomial(2);
        Polynomial q = new Polynomial(p);
    }

}

那么问题是实例变量ab没有在复制构造函数中初始化。每个构造函数都是独立的,如果你想从一个内部执行操作,你必须通过调用一个通用的初始化函数来明确地做到这一点,例如

public class Polynomial {

    private int[] a;
    private int[] b;

    private void init(int length) {
        a = new int[length];
        b = new int[length];
    }

    public Polynomial(int length) {
        init(length);
    }

    public Polynomial(Polynomial poly)
    {
        init(poly.a.length);
        for(int i = 0; i < a.length; i++)
            a[i] = poly.a[i];
        for(int i = 0; i < b.length; i++)
            b[i] = poly.b[i];
    }


    public static void main(String[] args) {
        Polynomial p = new Polynomial(2);
        Polynomial q = new Polynomial(p);
    }

}
于 2013-01-22T19:02:14.457 回答
0

你可以只使用:

public Polynomial(Polynomial poly) {
    a=poly.a.clone(); 
    b=poly.b.clone();
    }

这将在一个步骤中创建和复制数组。

于 2013-01-22T19:07:32.623 回答