Someone
Someone

Reputation: 551

Fixed number of generic objects which can be iterated over

I have a class which always holds four objects:

class Foo<E> {
    Cow<E> a, b, c, d;
}

I want to be able to iterate over them, so ideally I'd like to use an array:

class Foo<E> {
    Cow<E>[] cows = new Cow<E>[4]; // won't work, can't create generic array
}

I don't want to use a list or a set since I want there to always be 4 Cow objects. What's the best solution for me?

Upvotes: 0

Views: 63

Answers (5)

newacct
newacct

Reputation: 122439

Cow<E>[] cows = (Cow<E>[])new Cow[4];

or

Cow<E>[] cows = (Cow<E>[])new Cow<?>[4];

Upvotes: 0

assylias
assylias

Reputation: 328598

If you want to preserve the genericity, you will have to reimplement something similar to a list and I don't think it is worth it.

You said:

The first is that you can add and remove elements to and from a list.

Well you can create an unmodifiable list:

List<E> list = Collections.unmodifiableList(Arrays.asList(a, b, c, d));

The second is that I'm creating a quadtree data structure and using a list wouldn't be too good for performance. Quadtrees have a lot of quadrants and using lists would decrease performance significantly.

First you can initialise the list to the right size:

List<E> list = new ArrayList<>(4);

Once you have done that, the list will only use a little bit more memory than an array (probably 8 bytes: 4 byte for the backing array reference and another 4 byte for the size).

And in terms of performance an ArrayList performs almost as good as an array.

Bottom line: I would start by using a list and measure the performance. If it is not good enough AND it is due to using a list instead of an array, then you will have to adapt your design - but I doubt that this will be your main issue.

Upvotes: 1

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

Use Collection instead of array:

List<Cow<E>> cows = new ArrayList<>(); // in Java 7

Or

List<Cow<E>> cows = new ArrayList<Cow<E>>(); //Java 6 and below

More information will show why it is IMPOSSIBLE to have arrays whit generics. You can see here

Upvotes: 0

Saket
Saket

Reputation: 3129

I will suggest creating a bounded list. Java does not have an inbuilt one however you can create a custom one using Google collections or use the one in Apache collections. See Is there a bounded non-blocking Collection in Java?

Upvotes: 0

Martin Dinov
Martin Dinov

Reputation: 8815

Use a generic ArrayList and simply have methods to insert values into your object, and do checks inside those methods, to make sure you don't end up having more than 4 Cow objects.

Upvotes: 0

Related Questions