java 如何在java中查找字符数组中是否存在元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14484558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find if an element exists within a character array in java
提问by Praveen Puglia
Here is the thing. I have a character array as follows..
这是事情。我有一个字符数组如下..
char[] modes = new char[] { 'm', 'q', 'h', 'y' };
Now I want to provide the user with the option to enter a character. If it exists in the modes
array, I'll do the necessary. For that I used...
现在我想为用户提供输入字符的选项。如果它存在于modes
数组中,我会做必要的。为此我用...
//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);
But strangely ifExists
returns false
.
却诡异地ifExists
返回false
。
- Any Ideas where am I doing wrong?
- If this is a bad way of doing it, please suggest a way.
- 任何想法我在哪里做错了?
- 如果这是一种不好的方式,请提出一种方法。
回答by NickJ
I think it's Autoboxing - the contains() method takes an object, not a primitive.
我认为这是自动装箱 - contains() 方法接受一个对象,而不是一个原始对象。
If you use Character instead of char it will work:
如果您使用 Character 而不是 char 它将起作用:
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);
returns true
返回真
回答by Pat Burke
The Arrays.asList() method is returning a List of char[] and not a List of char like you are expecting. I would recommend using the Arrays.binarySort() method like so:
Arrays.asList() 方法返回一个 char[] 列表,而不是您期望的 char 列表。我建议使用 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);
回答by sunleo
I didn't find any problem with your code and try this,
我没有发现你的代码有任何问题,试试这个,
If you use this kind of Colletions then you can do lots of operations using methods available defaultly...
如果您使用这种集合,那么您可以使用默认可用的方法进行大量操作...
List<Character> l = new ArrayList<Character>();
l.add('a');
l.add('b');
l.add('c');
System.out.println(l.contains('a'));
回答by RNJ
回答by Jose Tepedino
You could also use String indexOf:
您还可以使用字符串 indexOf:
boolean ifExists = new String(modes).indexOf(mode) >= 0;
or
或者
boolean ifExists = "mqhy".indexOf(mode) >= 0;