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 个数组并比较条目,但无法获得有效的代码

解决方法

  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;
    }