0

I am trying to create a generic class in java like this

public class Cache <K,V> {

  private Entry<K,V>[][] cache;

  public Cache(int setCount, int arity){

      this.cache = new Entry<K,V>[setCount][arity];
}

Now java tells me I can not declare a generic array? I know that in C I could just lay this out in memory. Does anyone know how this should be done in java?

2 Answers 2

4

You can directly just use,

this.cache = new Entry[setCount][arity];

This will generate a warning similar to,

Type safety: The expression of type Entry[][] needs unchecked conversion to conform to Entry[][]

But you have to live with it, or you can suppress it with @SuppressWarnings("unchecked").

Note that since cache is of type Entry<K,V>[][], the generics behavior still holds good for it.

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

Comments

1

Does anyone know how this should be done in java?

Use an ArrayList (within a ArrayList) instead, something like...

private List<List<Entry<K,V>> cache;

and then you might initialise it using something like...

this.cache = new ArrayList<>(setCount);

Now, it's up to you if you want to pre-add the child List's or not. You could lazy create it, or create it with the constructor, for example...

for (int index = 0; index < setCount; index++) {
    cache.add(new ArrayList<>(arity));
}

depending on your needs

Take a look at Collections Trail for more details

2 Comments

Thank you so much for your answer, I went with the below answer because I am concerned about access time. Is this worry appropriate?
Well ArrayList is a implementation of List which is backed by an array internally, so, no, the access time would be just about the same (allowing for an additional method call), it's also dynamically resizable, so you can grow or shrink it if you want, no extra code on your part. Pretty much anywhere you might use an array, you could use an ArrayList instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.