David Mathers
David Mathers

Reputation: 165

Creating an Array object with generics

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!

Upvotes: 2

Views: 85

Answers (1)

Jens
Jens

Reputation: 9416

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

Upvotes: 6

Related Questions