How do I determine whether an array contains a particular value in Java?

后端 未结 29 2744
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};

Given

29条回答
  •  再見小時候
    2020-11-21 05:40

    For what it's worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().

    When using a 10K array size the results were:

    Sort & Search   : 15
    Binary Search   : 0
    asList.contains : 0
    

    When using a 100K array the results were:

    Sort & Search   : 156
    Binary Search   : 0
    asList.contains : 32
    

    So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.

    I would think those are the results most people would expect. Here is the test code:

    import java.util.*;
    
    public class Test
    {
        public static void main(String args[])
        {
            long start = 0;
            int size = 100000;
            String[] strings = new String[size];
            Random random = new Random();
    
    
            for (int i = 0; i < size; i++)
                strings[i] = "" + random.nextInt( size );
    
            start = System.currentTimeMillis();
            Arrays.sort(strings);
            System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
            System.out.println("Sort & Search : " + (System.currentTimeMillis() - start));
    
            start = System.currentTimeMillis();
            System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
            System.out.println("Search        : " + (System.currentTimeMillis() - start));
    
            start = System.currentTimeMillis();
            System.out.println(Arrays.asList(strings).contains( "" + (size - 1) ));
            System.out.println("Contains      : " + (System.currentTimeMillis() - start));
        }
    }
    

提交回复
热议问题