在参数上使用 Casting
Use of Casting on a parameter
IFrame 是一个接口(我不应该修改),而 Frame 是扩展 class。
我需要使用转换或实例来引用 f 作为 Frame 而不是 os IFrame。
我怎样才能做到这一点?
public class Frame implements IFrame{
private int numRows;
private char code[][];
@Override
public void replace(IFrame f) {
for (int i=0; i<numRows; i++){
for (int o=0; o<numRows; o++){
(Frame f).code[i][o] = this.code[i][o];
}
}
}
}
((Frame) f).code[i][o] = this.code[i][o]
应该有效,但我建议您在复制之前测试传递的参数是否实际上是 Frame
的实例,以避免转换错误。此外,您应该确保传递的 Frame
的 numRows
大于或等于被调用实例之一:
public void replace(IFrame iFrame) {
if (iFrame instanceof Frame) {
Frame f = (Frame) iFrame;
if (f.numRows < this.numRows) {
// Do what you want to do if the provided frame has fewer rows than this frame
return; // Return in the if condition, this way you do not proceed to the for loop causing an IndexOutOfBounds exception
}
for (int i=0; i<numRows; i++){
for (int o=0; o<numRows; o++){
(Frame f).code[i][o] = this.code[i][o];
}
}
}
}
}
您还需要一组括号用于演员表:
public void replace(IFrame f) {
for (int i = 0; i < numRows; i++) {
for (int o = 0; o < numRows; o++) {
((Frame) f).code[i][o] = this.code[i][o];
}
}
}
还建议在方法的第一条语句中验证参数的运行时类型,并做出适当的反应,例如:
if (!(f instanceof Frame))
throw new IllegalArgumentException("Need an instance of Frame. Got an instance of " + f.getClass().getName() + ".");
数组复制的性能优化版本可以通过使用System.arraycopy:
来实现
for (int i = 0; i < numRows; i++) {
System.arraycopy(this.code[i], 0, ((Frame) f).code[i], 0, numRows);
}
IFrame 是一个接口(我不应该修改),而 Frame 是扩展 class。
我需要使用转换或实例来引用 f 作为 Frame 而不是 os IFrame。
我怎样才能做到这一点?
public class Frame implements IFrame{
private int numRows;
private char code[][];
@Override
public void replace(IFrame f) {
for (int i=0; i<numRows; i++){
for (int o=0; o<numRows; o++){
(Frame f).code[i][o] = this.code[i][o];
}
}
}
}
((Frame) f).code[i][o] = this.code[i][o]
应该有效,但我建议您在复制之前测试传递的参数是否实际上是 Frame
的实例,以避免转换错误。此外,您应该确保传递的 Frame
的 numRows
大于或等于被调用实例之一:
public void replace(IFrame iFrame) {
if (iFrame instanceof Frame) {
Frame f = (Frame) iFrame;
if (f.numRows < this.numRows) {
// Do what you want to do if the provided frame has fewer rows than this frame
return; // Return in the if condition, this way you do not proceed to the for loop causing an IndexOutOfBounds exception
}
for (int i=0; i<numRows; i++){
for (int o=0; o<numRows; o++){
(Frame f).code[i][o] = this.code[i][o];
}
}
}
}
}
您还需要一组括号用于演员表:
public void replace(IFrame f) {
for (int i = 0; i < numRows; i++) {
for (int o = 0; o < numRows; o++) {
((Frame) f).code[i][o] = this.code[i][o];
}
}
}
还建议在方法的第一条语句中验证参数的运行时类型,并做出适当的反应,例如:
if (!(f instanceof Frame))
throw new IllegalArgumentException("Need an instance of Frame. Got an instance of " + f.getClass().getName() + ".");
数组复制的性能优化版本可以通过使用System.arraycopy:
来实现for (int i = 0; i < numRows; i++) {
System.arraycopy(this.code[i], 0, ((Frame) f).code[i], 0, numRows);
}