【问题标题】:how to set, get a variable in java如何在java中设置,获取变量
【发布时间】:2021-04-27 07:52:49
【问题描述】:

我必须实现这个类和 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 个数组并比较条目,但无法获得有效的代码。

【问题讨论】:

  • 只是一个提示:由于var在java中成为了一个关键字,所以将它用作变量名并不是最好的主意。

标签: java variables get set


【解决方案1】:
  1. 您需要有一个类字段,用于存储设置的值:

    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?
     }
    
  2. 现在,您应该可以创建 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;
    }
    

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2011-11-27
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 2010-09-16
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多