简体   繁体   中英

Is there a way to implement a type-safe vector in Java?

I am trying to implement a vector for my coding assignment using Java. I want to put information about the dimension of a vector into its type to make my code more type-safe.

I tried to represent a vector as int[n] , but the following code didn't compile.

public static int[n] createVector(int n) {
    return new int[n];
}

The output of the compilation:

src\Main.java:59: error: ']' expected
    public static int[n] createVector(int n) {
                      ^
src\Main.java:59: error: ';' expected
    public static int[n] createVector(int n) {
                       ^
src\Main.java:59: error: invalid method declaration; return type required
    public static int[n] createVector(int n) {
                         ^
3 errors

I think the problem is that all int arrays in java have the same type and I can't specialize it.

Is there a way to do it in Java?

How will you deal with vectors of different dimensions? Is this one type or different types in term of types ?

 class Vector<T> { private final int dimension; private T[] elements; public Vector(Class<T> clazz, int dimension) { this.dimension = dimension; this.elements = (T[]) Array.newInstance(clazz, dimension); } // any useful methods here }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM