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

后端 未结 29 2804
予麋鹿
予麋鹿 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:50

    Try this:

    ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
    
    // use add() method to add elements in the list
    arrlist.add(20);
    arrlist.add(25);
    arrlist.add(10);
    arrlist.add(15);
    
    boolean retval = arrlist.contains(10);
    if (retval == true) {
        System.out.println("10 is contained in the list");
    }
    else {
        System.out.println("10 is not contained in the list");
    }
    
    0 讨论(0)
  • 2020-11-21 05:51

    You can use ArrayUtils.contains from Apache Commons Lang

    public static boolean contains(Object[] array, Object objectToFind)

    Note that this method returns false if the passed array is null.

    There are also methods available for primitive arrays of all kinds.

    Example:

    String[] fieldsToInclude = { "id", "name", "location" };
    
    if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
        // Do some stuff.
    }
    
    0 讨论(0)
  • 2020-11-21 05:52

    Actually, if you use HashSet<String> as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.

    It all depends on how your code is set up, obviously, but from where I stand, the order would be:

    On an unsorted array:

    1. HashSet
    2. asList
    3. sort & binary

    On a sorted array:

    1. HashSet
    2. Binary
    3. asList

    So either way, HashSet for the win.

    0 讨论(0)
  • 2020-11-21 05:54

    You can check it by two methods

    A)By converting the array into string and then check the required string by .contains method

     String a=Arrays.toString(VALUES);
        System.out.println(a.contains("AB"));
        System.out.println(a.contains("BC"));
        System.out.println(a.contains("CD"));
        System.out.println(a.contains("AE"));
    

    B)this is a more efficent method

     Scanner s=new Scanner(System.in);
    
    
       String u=s.next();
       boolean d=true;
        for(int i=0;i<VAL.length;i++)
        {
            if(VAL[i].equals(u)==d)
                System.out.println(VAL[i] +" "+u+VAL[i].equals(u));  
    
        }
    
    0 讨论(0)
  • 2020-11-21 05:57

    As I'm dealing with low level Java using primitive types byte and byte[], the best so far I got is from bytes-java https://github.com/patrickfav/bytes-java seems a fine piece of work

    0 讨论(0)
提交回复
热议问题