How to get index of value in array?

前端 未结 7 880
無奈伤痛
無奈伤痛 2021-01-26 07:37

I have an array like this :

String[] array = { \"Designation1\", \"Designation2\", \"Designation3\" };

If user put \"Designation2\" as input th

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 08:15

    Consider using List instead of array (of just wrap your array in List). This way you will have access to method like indexOf(element) which will return index of first founded element, of -1 if no element in array was found.

    String[] array = { "Designation1", "Designation2", "Designation3" };
    List list = Arrays.asList(array);
    
    System.out.println(list.indexOf("Designation2")); //prints 1
    System.out.println(list.indexOf("foo"));          //prints -1
    

提交回复
热议问题