java - 错误 "cannot resolve method"

标签 java oop vector

我正在创建一个用于教育目的的Vector 类。这个类有标准的 getter 和 setter,现在我想添加对添加两个 vector 的支持。

当我尝试调用 result.setVectorValue 时,收到错误无法解析 setVectorValue 方法。我怎样才能克服我的困难?

这是我的类(class)的完整代码:

public class Vector <T1> {
    private T1[] vectorArray;

    public Vector(){
    }

    public Vector(T1[] a){
        this.vectorArray = a;
    }

    public void setVector(T1[] a){
        this.vectorArray = a;
    }

    public void setVectorValue(T1 value, int index){
        this.vectorArray[index] = value;
    }

    public T1[] getVector(){
        return this.vectorArray;
    }

    public T1 getVectorValue(int index){
        return this.vectorArray[index];
    }

    public int getVectorLength(){
        return this.vectorArray.length;
    }

    public String toString() {
        if (vectorArray == null)
            return null;
        return vectorArray.getClass().getName() + " " + vectorArray;
    }

    public T1[] plus(T1[] inputVector, T1[] whatToPlusVector){
        Vector <T1> result = new Vector<T1>();

        int index=0;
        for(T1 element : inputVector){
            result.setVectorValue(element, index);
            index++;
        }
        for(T1 element : whatToPlusVector){
            result.setVectorValue(element, index);
            index++;
        }
        return result;
    }
}

最佳答案

您的无参数构造函数(采用零个参数的构造函数)不会初始化内部 vectorArray 。如果使用无参数构造函数,则您的 vectorArray将保持null 。在你的plus()方法您使用无参数构造函数,因此您无法设置此 result 的任何元素 vector 。您应该使用长度为以下的初始数组来创建它:

int length = inputVector.getVectorLength() + whatToPlusVector.getVectorLength();

由于数组必须是通用类型 T1这很棘手。你不能只写new T1[length] .

对于通用数组创建,请参阅以下内容: How to create a generic array in Java?

所以在你的 plus() 中你应该这样做的方法:

int length = inputVector.getVectorLength() + whatToPlusVector.getVectorLength();
// You need the class of T1 to be able to create an array of it:
Class<?> clazz = inputVector.getVector().getClass().getComponentType();

T1[] array=(T[])Array.newInstance(clazz, length);
Vector <T1> result = new Vector<>(array);
// And the rest of your plus() method.

最后:您的 plus()方法被声明返回 T1[]所以要么返回 result.getVector()或者声明它返回 Vector<T1>然后你可以返回 result类型为 Vector<T1> 的局部变量.

关于java - 错误 "cannot resolve method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25153081/

相关文章:

c++ - 为什么 vector 的容量和大小不同?

java - 如何将 BST 中的删除方法从递归切换为迭代?

java - 小程序不适用于 chrome

java - Apache Derby 插入速度很慢

限制访问 addprop 的 Matlab 动态属性

java - 如何从基类实例中找出子类?

oop - 我如何在 lua love2d (OOP) 中使用类

c++ - 模板函数中 std::string 的类型推断失败

java - 许可基于 Java Web 的应用程序

c++ - vector<double>::size_type 与 double