简体   繁体   中英

No output when checking an element in an ArrayList in Java

I have declared a string ArrayList in Java, now when I fill the entire list and I check if one element is inside with the ArrayList.contains(value) method and I want to print if it exists or not I get no output. I am wondering why as the list.contains("Red") method should return TRUE .

Code snippet :

import java.util.ArrayList;

public MyClass{
    public static void main(){

    ArrayList<String> list = new ArrayList<String>(10);

    list.add("Green");
    list.add("Orange");
    list.add("Red");
    list.add("Black");
    list.add("White");

    boolean test = list.contains("Red");

    if(test)
        System.out.println("True");

    else
        System.out.println("False");
    }
}

Everything is OK in your code. But argument is missing. As JVM starts executing the java program it searches for the main method having this signature(ie String array).

So your Main Method should be like

public static void main(String[] args)

And class modifier also missing in your class.

Use public class MyClass instead of public MyClass

Use the below code, It works in my local, There are a couple of things missing in your code, Class modifier is missing and there is not " String[] args ".Also, I did a bit of refactoring of your code. Hope this helps for you

package com.sample.service;

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Green");
        list.add("Orange");
        list.add("Red");
        list.add("Black");
        list.add("White");

        boolean test = list.contains("Red");
        System.out.println(test);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM