简体   繁体   English

为什么Arrays.asList(charArray).indexOf总是返回-1?

[英]Why does Arrays.asList(charArray).indexOf always return -1?

So I am trying to make a method that you send a simple string to, which is then broken up char by char in a for loop, with each char from the array "alpha" transformed into its equivalent value in "beta", they are then all concatenated using StringBuilder and sent back as the "output", as shown here: 所以我试图创建一个方法,你发送一个简单的字符串,然后在for循环中由char分解char,数组“alpha”中的每个char转换为“beta”中的等效值,它们是然后所有连接使用StringBuilder并作为“输出”发回,如下所示:

Code: I have simplified the entire class and all variable names to improve readability. 代码:我简化了整个类和所有变量名称以提高可读性。

import java.util.Arrays;

public class Test {
    private 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'};

    public String getAlpha(String input) {

        StringBuilder output = new StringBuilder();

        for (int i = 0; i < input.length(); i++) {

            char c = input.charAt(i);
            int index;

            if (Character.isLetter(c)) {
                try {
                    index = Arrays.asList(alpha).indexOf(Character.toUpperCase(c));

                    System.out.println(c); //debug
                    System.out.println(index); //debug

                    //output.append(beta[index]); //gets the index and applies it to beta (unnecessary for this example)
                } catch(ArrayIndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            } else {
                output.append(c);
            }
        }

        return output.toString();
    }

    public static void main(String[] args) {
        Test test1 = new Test();

        test1.getAlpha("Hello");
    }
}

The problem I am having is that my index for each char consistently causes an ArrayIndexOutOfBounds exception, due to the indexOf not being able to find the chars equivalent in the array "alpha". 我遇到的问题是我的每个char的索引始终导致ArrayIndexOutOfBounds异常,因为indexOf无法在数组“alpha”中找到等效的字符。

Am I doing something wrong? 难道我做错了什么? Obviousy, but I cannot understand what / why its is not getting any index for any char. 显而易见,但我无法理解为什么/为什么它没有为任何char获取任何索引。 Any help would be appreciated thanks. 任何帮助将不胜感激。

Input: 输入:

"Hello"

Output: debug 输出: debug

H
-1
e
-1
l
-1
l
-1
o
-1
char[] alpha = {...};
index = Arrays.asList(alpha).indexOf(Character.toUpperCase(c));

The problem is subtle. 问题很微妙。 Arrays.asList(T...) expects an array of T where T extends Object . Arrays.asList(T...)需要一个T数组,其中T extends Object It doesn't work like you'd expect if you pass an array of primitives. 如果传递一组基元,它就不会像你期望的那样工作。 In that case, it thinks T = char[] and gives you back a List<char[]> containing a single element, alpha . 在这种情况下,它认为T = char[]并返回包含单个元素alphaList<char[]>

A List<char[]> contains char arrays, not chars, so the indexOf call always returns -1 . List<char[]>包含char数组,而不是chars,因此indexOf调用始终返回-1

You might wonder why you don't get a compile-time error. 您可能想知道为什么不会出现编译时错误。 Shouldn't indexOf expect to be passed a char[] reference if it's being called on a List<char[]> ? 如果在List<char[]>上调用它,那么indexOf是否应该传递一个char[]引用? Well, surprisingly, no. 好吧,令人惊讶的是,没有。 indexOf 's signature is int indexOf(Object) : it accepts any type of object, even ones unrelated to T . indexOf的签名是int indexOf(Object) :它接受任何类型的对象,甚至是与T无关的对象。

You could use Arrays.binarySearch . 你可以使用Arrays.binarySearch That would work since your array is sorted. 这可以工作,因为您的数组已排序。 Or you could use a String instead of a char[] array. 或者您可以使用String而不是char[]数组。

Another method would be to do some simple math if the character is in range. 如果角色在范围内,另一种方法是做一些简单的数学运算。

char uc = Character.toUpperCase(c);
if (uc >= 'A' && uc <= 'Z') {
    index = uc - 'A';
}

Is this what you are trying to do? 这是你想要做的吗?

You can avoid the OutOfBounds (or linear/binary search) entirely by taking advantage of the fact that char values are mapped to ASCII int values and you can do simply math on them to get character positions. 您可以通过利用char值映射到ASCII int值的事实完全避免OutOfBounds(或线性/二进制搜索),并且您可以简单地对它们进行数学运算以获得字符位置。

Output 产量

H
8
e
5
l
12
l
12
o
15

private final String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public String getAlpha(String input) {

    StringBuilder output = new StringBuilder();

    for (int i = 0; i < input.length(); i++) {

        char c = input.charAt(i);

        if (Character.isLetter(c)) {
            int index = Character.toUpperCase(c) - 'A' + 1;
            System.out.println(c); //debug
            System.out.println(index); //debug

            //output.append(beta[index]); //gets the index and applies it to beta (unnecessary for this example)

        } else {
            output.append(c);
        }
    }

    return output.toString();
}

The indexOf() is doing a comparison of objects. indexOf()正在对对象进行比较。 The Character.toUpperCase() returns a Character, but every item in the array is a char, so none match. Character.toUpperCase()返回一个Character,但数组中的每个项都是一个char,所以没有匹配。

If you change the char[] to a Character[], you'll get the behaviour you expect. 如果将char []更改为Character [],您将获得所期望的行为。

试试这个:index = new String(alpha).indexOf(Character.toUpperCase(c));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM