Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created July 14, 2014 02:39
Show Gist options
  • Select an option

  • Save adohe-zz/4c17e6303fe9da36ab97 to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/4c17e6303fe9da36ab97 to your computer and use it in GitHub Desktop.
How to check if an array (unsorted) contains a certain value?
package com.westudio.java;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Actually, if you really need to check if a value is contained in some array/collection efficiently,
* a sorted list or tree can do it in O(log(n)) or hashset can do it in O(1).
*/
public class CheckExists {
private static boolean exists(String[] strings, String str) {
return Arrays.asList(strings).contains(str);
}
private static boolean existsTwo(String[] strings, String str) {
Set<String> set = new HashSet<String>(Arrays.asList(strings));
return set.contains(str);
}
private static boolean existsThree(String[] strings, String str) {
for (String s: strings) {
if (s.equals(str)) {
return true;
}
}
return false;
}
/**
* This method can only be used when the array is sorted
* @param strings
* @param str
* @return
*/
private static boolean existsFour(String[] strings, String str) {
int a = Arrays.binarySearch(strings, str);
if (a < 0) {
return false;
}
return true;
}
public static void main(String[] args) {
String[] strs = {"a", "v", "c", "d", "e"};
System.out.println(exists(strs, "a"));
System.out.println(existsTwo(strs, "a"));
System.out.println(existsThree(strs, "a"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment