11

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:

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?

0

5 Answers 5

13

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

if (Arrays.asList(array).contains("whatever")) // do your thing 
Sign up to request clarification or add additional context in comments.

Comments

3
String[] array = {"x", "y", "z"}; if (Arrays.asList(array).contains("x")) { System.out.println("Contains!"); } 

Comments

2

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. 

Comments

1

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

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 array to search can take O(N) in the worst case.

Comments

1

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

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

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.equals(myVar)) { } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.