Question

Is it possible in Java to parametrize a data structure so that it can only hold arrays of a certain length. I am writing a program that deals with 3d objects and I want a list that will only hold vectors stored as 3 doubles in an array or double[3]. The code below wont compile.

Vector<double[3]> myList = new Vector<double[3]>();

Is there a way to restrict the size of an array stored in a data structure?

Was it helpful?

Solution

Yes, create a sub class of that data structure and override add/ put method of that data structure, check before adding whether length of array is 3 or not.

Below is the example:

import java.util.Vector;

public class SubClassArrayList<E> extends Vector<E> {

    public boolean add(E e , int length) {
        if (e instanceof Object[] && ((Object[]) e).length == length) {
            return super.add(e);
        }
        else return false;
    }

}

Above will also work for ArrayList

OTHER TIPS

In addition to Vishrant's answer, you can write a custom class, say Coord, that has an array member that holds doubles and use that.

public class Coord {
   private double[] values;

   public Coord(double[] values) {
      //check whether values array has a length of 3
      this.values = values;
   }

   //add getter and setter, check the size of the input array in the setter method
}

Then, you can use the class above in the java.util.* data structures. You should implement hashCode() and equals() methods if you are going to use HashMap or HashSet.

Not directly related to the question but I wanted to say that you should not use Vector unless you want thread-safety. Prefer classes implementing List.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top