Java - arraylist1.get(arraylist2.indexOf(下一个字符)) returns -1

Java - arraylist1.get(arraylist2.indexOf(nextCharacter)) returns -1

我有(对于这个例子)两个 ArrayList。明文字母表和加密字母表。我想从明文字母表中取出一个字母,然后从加密字母表中的相应索引中获取字母。但是,它总是 return 将索引设置为 -1,即使该条目存在。

public class Rotor {
    String currentIndex;
    private ArrayList rotorType = new ArrayList();
    private ArrayList control = new ArrayList();
    private final char[] alpha = new char[]{
        'A', 'B', 'C', 'D', 'E', 'F', 'G',
        'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U',
        'V', 'W', 'X', 'Y', 'Z'};

    static char[] I = new char[]{
        'E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q',
        'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H',
        'X', 'U', 'S', 'T', 'A', 'I', 'B', 'R',
        'C', 'J'};

    public Rotor(char[] rotor) {
        for (int i = 0; i < 25; i++) {
            rotorType.add(rotor[i]);
            control.add(alpha[i]);
        }
    }

    public void convert(String nextCharacter) {
        currentIndex = String.valueOf(rotorType.get(control.indexOf(nextCharacter)));
    }
}

什么会导致 return 索引 -1?

首先:代码使用原始类型,we should avoid

其次:因为Sotirios Delimanolis pointed out Character不是String。因此,如果我们问一个ArrayList包含Character,它是否包含一个String,它总是returnfalse。这导致了问题。

第三:字母表有26个字符,而不是25个。因此,for循环应该迭代到i <= 26,而不是i <= 25

我稍微重写了代码,结果似乎是正确的。

import java.util.ArrayList;

public class Main {
    String currentIndex;
    private ArrayList<Character> rotorType = new ArrayList<Character>();
    private ArrayList<Character> control = new ArrayList<Character>();
    
    static final char[] alpha = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G',
        'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U',
        'V', 'W', 'X', 'Y', 'Z'};

    static final char[] I = {
        'E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q',
        'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H',
        'X', 'U', 'S', 'T', 'A', 'I', 'B', 'R',
        'C', 'J'};

    public Main(char[] rotor) {
        assert (alpha.length == rotor.length) : "rotor must be of same length as alpha.";
        for (int idx = 0; idx < alpha.length; ++idx) {
            rotorType.add(rotor[idx]);
            control.add(alpha[idx]);
        }
    }

    public void convert(char nextCharacter) {
        currentIndex = String.valueOf(rotorType.get(control.indexOf(nextCharacter)));
    }
}