2

So I'm trying to create a simple program that allows for me to put an array of Int, String, double.... to an object and the print it:

public class Array<E> {

    private E[] data;
    private int size;

    public Array(int size, E[] data)
    {
        this.size=size;
        for(int i=0; i<size; i++) this.data[i]=data[i];
    }

    public String toString()
    {
        String s=new String();
        for(int i=0; i<size; i++) s+=data[i]+" ";
        return s;
    }
}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int A[]= {1, 3, 5, 7};
        Array<Integer> niza=new Array<Integer>(4, A);
        System.out.println(niza.toString());
    }

}

However it gives me this error whenever I try to create the object:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Array(int, int[]) is undefined

at test.Main.main(Main.java:8)

Any ideas of what's causing the problem and a possible solution?

Thanks in advance!

3
  • 4
    Declare your array as this :Integer A[]= {1, 3, 5, 7}; Commented Oct 23, 2017 at 8:13
  • Nope it's still not working. Commented Oct 23, 2017 at 8:15
  • 1
    @AndrewTobilko it is his own... but the current problem is explained in Jens answer, he now have NPE due to this.data being null Commented Oct 23, 2017 at 8:20

1 Answer 1

6

The problem is that

    int A[]= {1, 3, 5, 7};
    Array<Integer> niza=new Array<Integer>(4, A);

declares an array of ints, while the constructor expects Integer[]. int is a fundamental type, and is a different type than Integer. The compiler converts between int and Integer when possible and needed, but this conversion is not defined for arrays.

If you declare your array as

    Integer A[]= {1, 3, 5, 7};
    Array<Integer> niza=new Array<Integer>(4, A);

your code will compile, but fail with a NullPointerException because the member data is not initialized. You can easily fix that with

private final E[] data;

public Array(int size, E[] data)
{
    this.size=size;
    this.data = Arrays.copyOf(data, size);
}

Although I would prefer to use ArrayList instead of arrays...

Sign up to request clarification or add additional context in comments.

2 Comments

Yes that's exactly what I did and it failed with a NullPointerException. Why is it doing that?
your data field is not initialized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.