wowohweewah
wowohweewah

Reputation: 429

Storing a List of Arrays Efficiently in Java

Long story short, I need a list of arrays that can be of varying types (int, double, String, byte, etc.). Now the thing is I have gotten this to work with an unspecified ArrayList object, but every time I retrieve an array from the ArrayList, I'm converting it to the type of array I want e.g. ((double[]) arraylist.get(j))[i] then doing what I have to do.

But my worry is: This is a program that will be iterating hundreds of times and I feel like this is very inefficient and slow. Would rather just have a list of references instead of requiring constant conversions. So any thoughts on alternatives would be appreciated.

Upvotes: 1

Views: 478

Answers (2)

Xeon
Xeon

Reputation: 5989

As all others are saying - there is no conversion - its just a cast.

But in case you don't want write this cast you can wrap this listarray in class and provide a method:

public <T> T get(int indexOfArray, int indexInArray) {
    return (T) ((T[]) arraylist.get(indexOfArray))[indexInArray];
}

so that you can use within your code:

MyClassWithArrayList l = new MyClassWithArrayList(...);
...
double d = l.get(1, 2);

but of course you must be completely sure that array at 1 index is of double type (there would be cast exceptions)

or if you know that always there will be an array of doubles at 1 index you could write

public interface AppConstants {
    public static final int DOUBLE_TABLE_INDEX = 1;
    ...

and use:

double d = l.get(AppConstants.DOUBLE_TABLE_INDEX, 2);

Upvotes: 2

Cubic
Cubic

Reputation: 15673

There's no actual conversion done, just a type check on runtime. If you just need to do this a few hundred times per second it shouldn't be much of an issue, though storing unrelated data sounds as if you are attacking your problem from the wrong angle anyways (of course I might be wrong, but I can't think of a situation in which this would be required or preferred).

Upvotes: 6

Related Questions