Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 参数化数据结构以容纳特定大小的数组?_Java_Arrays_Data Structures_Vector - Fatal编程技术网

Java 参数化数据结构以容纳特定大小的数组?

Java 参数化数据结构以容纳特定大小的数组?,java,arrays,data-structures,vector,Java,Arrays,Data Structures,Vector,在Java中,是否可以对数据结构进行参数化,使其只能容纳一定长度的数组。我正在编写一个处理3d对象的程序,我想要一个列表,该列表将只保存存储为数组中3个双精度向量或双精度向量[3]。下面的代码无法编译 Vector<double[3]> myList = new Vector<double[3]>(); Vector myList=new Vector(); 是否有方法限制存储在数据结构中的数组的大小?是的,创建该数据结构的子类并覆盖该数据结构的add/put方法,在

在Java中,是否可以对数据结构进行参数化,使其只能容纳一定长度的数组。我正在编写一个处理3d对象的程序,我想要一个列表,该列表将只保存存储为数组中3个双精度向量或双精度向量[3]。下面的代码无法编译

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

是否有方法限制存储在数据结构中的数组的大小?

是的,创建该数据结构的子类并覆盖该数据结构的
add
/
put
方法,在添加数组长度是否为3之前检查

下面是一个例子:

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;
    }

}
import java.util.Vector;
公共类子类列表扩展向量{
公共布尔加法(E,int-length){
if(对象[]的实例e&((对象[])e).length==length){
返回super.add(e);
}
否则返回false;
}
}

除了Vishrant的答案之外,您还可以编写一个自定义类,比如Coord,它有一个数组成员,该数组成员包含双精度数并使用它

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
}
然后,您可以在java.util.*数据结构中使用上面的类。如果要使用HashMap或HashSet,应该实现hashCode()和equals()方法

与这个问题没有直接关系,但我想说的是,除非您想要线程安全,否则不应该使用Vector。更喜欢实现列表的类