Android - Check whether a value exist in an Array

前端 未结 5 1284
挽巷
挽巷 2021-02-01 01:24

I have an array named \"bob\" which contains values.

String[] bob = { \"this\", \"is\", \"a\", \"really\", \"silly\", \"list\" };

How can I kno

相关标签:
5条回答
  • 2021-02-01 01:34

    Convert the Array to List using static Arrays.asList(T) and check with List.contains(Object) to check if an object exists in the retuned collection.

        String[] bob = { "this", "is", "a", "really", "silly", "list" };
               System.out.println(Arrays.asList(bob).contains("silly"));
    

    Traditional way however would be to iterate over the array and check at each element using equals().

    0 讨论(0)
  • 2021-02-01 01:52

    Here is an easy way to do it:

        ArrayList list = new ArrayList(Arrays.asList(bob ));
        if (list.contains("silly")) {
                        // my array has silly !
                 }
    

    The idea is to convert your Array to a ListArray object. but it would consume extra memory, so make sure it is worth it before using it.

    Edit

    If you are after peformance and saving memory you can use binary search algorthem instead: this way you don't have to allocate new objects:

    Arrays.sort(array) 
    int value = Arrays.binarySearch(array, "silly");
    if (value != -1) {
    // my array has silly !
    }
    
    0 讨论(0)
  • 2021-02-01 01:55

    You can use List#contains method. For that you need to convert your array to a list. You can use Arrays#asList() method fot that:

    String[] bob = { "this", "is", "a", "really", "silly", "list" };
    
    if (Arrays.asList(bob).contains("silly")) {
        // true
    }
    
    0 讨论(0)
  • 2021-02-01 01:56

    above code does not work for me. primitive types not allowed i guess.

    got to do it manually:

    char[] charlist = {'a','b','c','d'}
    boolean arraycontains = false;
    char tester = 'c';
    for (int y=0;y<charlist.length;y++){
            if (charlist[y] == character) {
                    arraycontains = true;
                    break;
            }
    }
    
    if (arraycontains) {
        //true. array contains the tester;
    }
    else {
        //false. array does not contain the tester;
    }
    

    :)

    0 讨论(0)
  • 2021-02-01 01:57

    If you are going to check it a lot you may find it more efficient to use a HashSet:

    String[] bob = { "this", "is", "a", "really", "silly", "list" };
    Set<String> silly = new HashSet<String>(Arrays.asList(bob));
    boolean isSilly = silly.contains("silly");
    
    0 讨论(0)
提交回复
热议问题