如何解决java中如何设置、获取变量
我必须实现这个类和 2 个方法,但不知道如何实现。我如何设置变量并再次获取它? 这是我的出发点:
public class VariableStorage<T> implements IVariableStorage<T> {
public void set(T var);
public T get();
}
这是我尝试过的:
public void set(T var) {
char T = 1;
}
public T get() {
return T;
}
在第二步中,我必须实现这一点,但我真的不知道如何做到这一点:
public interface ITextStorage < T extends CharSequence > extends
IVariableStorage <T > {
/**
* Counts the number of equal characters in same positions of
* the texts stored in this ITextStorage and the other storage .
* Example : ’abcdef ’ and ’abba ’ have two matching characters
* in the first two positions .
*
* @param other the other text storage
* @return the number of matching characters
*/
public int countMatchingCharacters ( ITextStorage <? > other ) ;
}
我尝试创建 2 个数组并比较条目,但无法获得有效的代码。
解决方法
-
您需要有一个类字段,用于存储设置的值:
public class VariableStorage<T> implements IVariableStorage<T> { private T t; @Override public void set(T var) { t = var; } @Override public T get() { return t; // what will happen if t wasn't set and get() was called? } // is that expected behavior? }
-
现在,您应该能够创建 ITextStorage 的实现。
在方法中,你可以:
public int countMatchingCharacters(ITextStorage<?> other) { int matchingCharsCount = 0; for (int i = 0; i < this.t.get().length(); i++) { if(this.t.get().charAt(i) == other.get().charAt(i)){ matchingCharsCount++; } } return matchingCharsCount; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。