2

I am trying to make a generic array in java - in which i am having some issues - how can i make an array of Tuples which is of size 6 and has size a byte[] and a Integer inside?

Thanks

private Tuple<byte[], Integer>[] alternativeImages1 = new Tuple<byte[], Integer>[6];

class Tuple<F, S> {

    public final F first;
    public final S second;

    public Tuple(final F first, final S second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        final Tuple tuple = (Tuple) o;
        return this.first == tuple.first && this.second == tuple.second;
    }

    @Override
    public int hashCode() {
        int result = this.first != null ? first.hashCode() : 0;
        result = 31 * result + (this.second != null ? second.hashCode() : 0);
        return result;
    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Biscuit128
  • 5,218
  • 22
  • 89
  • 149
  • You cannot create arrays of types that take type parameters; that's a limitation of arrays in Java. This question has been asked before, for example: [Array of Generic List](http://stackoverflow.com/questions/7810074/array-of-generic-list) – Jesper Apr 17 '14 at 19:26

1 Answers1

7

Well you can use a raw type:

Tuple[] array = new Tuple[6];

Or you can make an unchecked conversion:

Tuple<byte[], Integer>[] array = (Tuple<byte[], Integer>[])new Tuple[6];

// or just this because raw types let you do it
Tuple<byte[], Integer>[] array = new Tuple[6];

Or you can use a List instead:

List<Tuple<byte[], Integer>> list = new ArrayList<Tuple<byte[], Integer>>();

I recommend using a List instead.

Choosing between the first two options, I would recommend the unchecked conversion because it will provide you with compile-time checks. However, it will not throw an ArrayStoreException if you put some other kind of Tuple in it.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • if you could use a fixed size list without needing to bounds check then i would use a list i think (especially if i could remove the default nulls) – Biscuit128 Apr 17 '14 at 19:28
  • Well it's true List has some different functionality from an array. It is possible though to extend ArrayList and make it behave more like an array. I could give you an example of that if you want though I'd recommend just getting used to using List's functionality. It's generally superior and there is rarely a reason to use an array except for low-level processing (such as I/O) or data structures where a fixed length is important (like a hash table). – Radiodef Apr 17 '14 at 19:52