如果 x 在 Java 中的数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22461470/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:51:57  来源:igfitidea点击:

If x in array in Java

java

提问by user3312175

In python, you can use a very simple if statement to see if what the user has entered (or just a variable) is in a list:

在 python 中,您可以使用一个非常简单的 if 语句来查看用户输入的内容(或只是一个变量)是否在列表中:

myList = ["x", "y", "z"]
myVar = "x"

if myVar in x:
    print("your variable is in the list.")

How would I be able to do this in Java?

我如何才能在 Java 中做到这一点?

采纳答案by Sotirios Delimanolis

If your array type is a reference type, you can convert it to a Listwith Arrays.asList(T...)and check if it contains the element

如果您的数组类型是引用类型,则可以将其转换为ListwithArrays.asList(T...)并检查它是否包含该元素

if (Arrays.asList(array).contains("whatever"))
    // do your thing

回答by DmitryKanunnikoff

String[] array = {"x", "y", "z"};

if (Arrays.asList(array).contains("x")) {
    System.out.println("Contains!");
}

回答by Elliott Frisch

Here is one solution,

这是一种解决方案,

String[] myArray = { "x", "y", "z" };
String myVar = "x";
if (Arrays.asList(myArray).contains(myVar)) {
    System.out.println("your variable is in the list.");
}

Output is,

输出是,

your variable is in the list.

回答by Brian

You could iterate through the array and search, but I recommend using the SetCollection.

您可以遍历数组并进行搜索,但我建议使用SetCollection。

Set<String> mySet = new HashSet<String>();
mySet.add("x");
mySet.add("y");
mySet.add("z");
String myVar = "x";

if (mySet.contains(myVar)) {
  System.out.println("your variable is in the list");
}

Set.contains()is evaluated in O(1)where traversing an arrayto search can take O(N)in the worst case.

Set.contains()在最坏的情况下O(1)遍历arrayto search 的位置进行评估O(N)

回答by Travis O'Donnell

Rather than calling the Arrays class, you could just iterate through the array yourself

您可以自己遍历数组,而不是调用 Arrays 类

String[] array = {"x", "y", "z"};
String myVar = "x";
for(String letter : array)
{
    if(letter.equals(myVar)
    {
         System.out.println(myVar +" is in the list");
    }
}

Remember that a String is nothing more than a character array in Java. That is

请记住,字符串只不过是 Java 中的字符数组。那是

String word = "dog";

is actually stored as

实际上存储为

char[] word = {"d", "o", "g"};

So if you would call if(letter == myVar), it would never return true, because it is just looking at the reference id inside the JVM. That is why in the code above I used

因此,如果您调用 if(letter == myVar),它将永远不会返回 true,因为它只是查看 JVM 中的引用 ID。这就是为什么在上面的代码中我使用

if(letter.equals(myVar)) { }