Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If x in array in Java [duplicate]

Tags:

java

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?

like image 891
user3312175 Avatar asked Mar 17 '14 17:03

user3312175


People also ask

How do you check if there are duplicates in an array Java?

One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.

Can you clone an array in Java?

Java allows you to copy arrays using either direct copy method provided by java. util or System class. It also provides a clone method that is used to clone an entire array.

How do you check if an array has all the same values Java?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check if an array contains the same value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


2 Answers

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
like image 161
Sotirios Delimanolis Avatar answered Oct 07 '22 20:10

Sotirios Delimanolis


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

if (Arrays.asList(array).contains("x")) {
    System.out.println("Contains!");
}
like image 28
DmitryKanunnikoff Avatar answered Oct 07 '22 18:10

DmitryKanunnikoff