Android - Check whether a value exist in an Array

前端 未结 5 1290
挽巷
挽巷 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: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 !
    }
    

提交回复
热议问题