Check for value in array

前端 未结 4 1892
时光说笑
时光说笑 2021-01-29 03:14

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn\'t there. The first part is working, but I tried to creat

4条回答
  •  -上瘾入骨i
    2021-01-29 03:49

    One simple solution is to use a Set:

    Set words = new HashSet();
    

    Add words with the add() method and check if a word is already added with contains(word) method.

    EDIT

    If you must use Arrays you can keep the array sorted and do a binary search:

    Arrays.sort(words);
    boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
    

提交回复
热议问题