LoginSignup
0
0

More than 3 years have passed since last update.

【Java】特定のオブジェクトが含まれているかを判定するListメソッド

Last updated at Posted at 2019-08-11

list.contains()

特定の要素があるかを判定し、booleanで返す

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));

    if(list.contains("banana")) {
            System.out.println("存在する");
        }else {
            System.out.println("存在しない");
        }
    }

list.indexOf()

特定の要素のINDEX番号をintで返し、存在しない場合は-1を返す

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));

        int x = list.indexOf("orange");
        System.out.println(x); 

        if(list.indexOf("orange") != -1) {
            System.out.println("存在する");
        }else {
            System.out.println("存在しない");
        }

    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0