Question:
How to test if an Array contains a certain value?
Answer:
Iterate through the array looking for a match
Or
Convert array to a list and use the method contains()
Or
Convert array to a list and use the method contains()
Code:
import java.util.*; public class TestArray { public static void main(String[] args) { String[] names = new String[] {"George","Paul","Ringo","John"}; System.out.println(Arrays.toString(names)); String who = "George"; // iterate through the array looking for a match for (int i = 0; i < names.length; i++){ if(who.equals(names[i])){ System.out.println( who + " is found"); break; } } // convert array to a list and use the method contains() List list = Arrays.asList(names); if(list.contains(who)){ System.out.println( who + " is found"); } } }
Output:
$ java TestArray [George, Paul, Ringo, John] George is found George is found