Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of fixed size Arrays in Java?

Tags:

java

arrays

list

Is it possible to create a List of arrays(with fixed size) in Java?

I have tried these methods and they both give me a syntax error:

List<int[]> failedParameters = new ArrayList<int[3]>();
List<int[]> failedParameters = new ArrayList<new int[3]>();

What am I doing wrong?

like image 229
greenfeet Avatar asked Oct 29 '25 08:10

greenfeet


2 Answers

No, you can't specify the array length as a Java type. However, you can wrap arrays in your own type. I'll let you decide if that is really practical (in case you have dozens of array lengths that you want to support):

class Int3 {
    // Use final to indicate that the array length will remain unchanged
    final int[] array = new int[3];
}

List<Int3> failedParameters = new ArrayList<Int3>();

Of course, if you go this far, why not just create an int-tuple of degree 3?

class Int3 {
    int v1;
    int v2;
    int v3;
}

List<Int3> failedParameters = new ArrayList<Int3>();
like image 142
Lukas Eder Avatar answered Oct 31 '25 00:10

Lukas Eder


You can use this method. It will not allow you to change the collection size (no add()/remove() operations).

List<> unmodiffableList = Collections.unmodifiableList(oListeRet);
like image 40
Beri Avatar answered Oct 30 '25 23:10

Beri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!