如何在java中查找字符数组中是否存在元素

如何在java中查找字符数组中是否存在元素,java,arrays,Java,Arrays,事情是这样的。我有一个字符数组,如下所示 char[] modes = new char[] { 'm', 'q', 'h', 'y' }; 现在我想为用户提供输入字符的选项。如果它存在于模式数组中,我将执行必要的操作。因为我曾经 //to take a character as input mode = input.next().charAt(0); //now to check if the array contains the character boolean ifExists = A

事情是这样的。我有一个字符数组,如下所示

char[] modes = new char[] { 'm', 'q', 'h', 'y' };
现在我想为用户提供输入字符的选项。如果它存在于
模式
数组中,我将执行必要的操作。因为我曾经

//to take a character as input
mode = input.next().charAt(0);
//now to check if the array contains the character
boolean ifExists = Arrays.asList(modes).contains(mode);
但奇怪的是,
ifExists
返回
false

  • 你知道我哪里做错了吗
  • 如果这是一种不好的方法,请建议一种方法

  • 我认为这是自动装箱-contains()方法接受对象,而不是原语

    如果使用字符而不是字符,则可以:

        Character[] modes = new Character[] { 'm', 'q', 'h', 'y' };
    
        //to take a character as input
        Character mode = "q123".charAt(0);
        //now to check if the array contains the character
        boolean ifExists = Arrays.asList(modes).contains(mode);
    
    返回true

    Arrays.asList()方法返回的是字符[]列表,而不是您期望的字符列表。我建议使用Arrays.binarySort()方法,如下所示:

        char[] modes = new char[] { 'm', 'q', 'h', 'y' };
    
        char mode = 'q';
    
        //now to check if the array contains the character
        int index = Arrays.binarySearch(modes, mode);
        boolean ifExists = index != -1;
        System.out.print(ifExists);
    

    我没有发现你的代码有任何问题,试试这个

    如果使用这种集合,则可以使用默认可用的方法执行许多操作…

    List<Character> l = new ArrayList<Character>();
    l.add('a');
    l.add('b');
    l.add('c');
    System.out.println(l.contains('a'));
    
    listl=newarraylist();
    l、 添加(“a”);
    l、 添加(‘b’);
    l、 加上(‘c’);
    System.out.println(l.contains('a'));
    
    您可以将其转换为字符串,然后运行


    然后,对于基元数组,它应该返回true或false。您还可以使用字符串indexOf:

    boolean ifExists = new String(modes).indexOf(mode) >= 0;
    


    “奇怪”的输入是什么?如果输入是
    a
    ,我不会觉得奇怪。我建议您在计算
    ifExists
    之前的代码行上打印
    模式的值和
    模式
    数组中所有内容的值。也许,某些值不是您所期望的……为什么您不在
    数组上使用
    二进制搜索
    方法?@Alex-我的输入是m@Perception-我总是可以使用二进制搜索..但我更想知道是否有内置的东西。或者类似的。在这种情况下,自动装箱不会自动生效吗?我很好奇为什么Java没有自动将原语包装为对象,它确实起了作用。查看contains()的源代码,它在引擎盖下使用了equals(),这在自动装箱字符上起作用。我很困惑-编辑-帕特·伯克有answer@Redandwhite-谢谢你这么问。我对此也很好奇,因为Java不支持autobox数组,所以Autoboxing不起作用。
    Arrays.asList
    的参数是
    T..
    ,并且
    T
    需要是对象类型。例如,
    Object[]array=newchar[0]将不会编译。为什么要连接该空字符串?请解释。将
    模式
    与空字符串串联只会将其转换为字符串。也可以使用
    String.valueOf(mode)
    获得基本相同的结果。谢谢matts。是的,我可以用String.valueOf代替。我正在将更多内容从chat转换为StringI我知道我在处理集合时可以使用很多东西。但是我想知道当它是一个基本数组时如何操作。对于给定的情况,它在所有情况下都有效。你能提供一个它不起作用的例子吗?实际上,
    数组。binarySearch(模式,'h')
    会导致
    -1
    ,其中负值表示键不在数组中。有趣的是,一定忽略了这一点!很好的调用。我想在搜索之前可以使用
    数组。排序(模式)
    ,但我不知道
    模式中的顺序在OP的程序中是否重要。(似乎没有,或者他一直在使用
    indexOf
    而不是
    contains
    )顺便说一句,
    binarySearch
    的文档也说它可以返回除
    -1
    之外的其他负值,所以可能应该使用
    ifExists=index>=0
    或更健壮的东西。干杯
    boolean ifExists = new String(modes).indexOf(mode) >= 0;
    
    boolean ifExists = "mqhy".indexOf(mode) >= 0;