我正在创建一个用于教育目的的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/