【问题标题】:How to call a method with different Generic type如何调用具有不同泛型类型的方法
【发布时间】:2019-10-26 12:11:31
【问题描述】:

我必须使用递归来实现这两种方法: - 第一个是在PositionList中的一个Node处返回一个值 - 第二个将加密的List<Integer> 转换为 (<Character>) 列表

在解密方法中,我试图调用 getPositon 方法但得到错误 "Recursion 类型中的方法getPosition(PositionList<E>, Position<E>, int) 不适用于参数(PositionList<Character>, Position<Integer>, int)"

我如何调用 .decrypt 给它一个 PositonList<Character> 和一个 Position<Integer>

public static <E> Position<E> getPosition(PositionList<E> l, Position<E> pos, int n) {

     if(n < 0) {
         pos = l.prev(pos);
         return getPosition(l, pos, n+1);
     }
     if(n > 0) {
         pos = l.next(pos);
         return getPosition(l, pos, n-1);
     }
     else {
         return pos;
     }
  }

  public static PositionList<Character> decrypt(PositionList<Character> alphabet, PositionList<Integer> encodedText) {

      PositionList<Character> newList;
      Position<Integer> pos; 


      if(counter <= alphabet.size()) {
          if(counter == 0) {
              pos = encodedText.first();
              value = pos.element();
          }
          if(counter > 0) {
              pos = encodedText.next(pos);
              value = pos.element();
          }
          newList.addLast(getPosition(alphabet, pos, value));
          counter++;
          return decrypt(alphabet, encodedText);
      }

      else {
          counter = 0;
          return newList;
      }
  }

【问题讨论】:

    标签: java generics methods


    【解决方案1】:

    您可以将多个泛型类型传递给这样的方法:

    public static <E, F> Position<F> getPosition(PositionList<E> l, Position<F> pos, int n) {
        ...
    }
    

    【讨论】:

    • 在这种情况下,.getPosition 中的 next 和 prev 方法会出现相同的错误: PositionList 类型中的方法 next(Position) 不适用于参数(位置
    • 也许您应该使用Position&lt;Character&gt; 而不是Position&lt;Integer&gt;?那么你就不需要两个泛型参数了。
    • 我必须使用 Position 因为解密方法得到的是 PositionList
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多