简体   繁体   English

在Java中检查ArrayList中的元素时无输出

[英]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. 我已经用Java声明了一个字符串ArrayList,现在当我填满整个列表时,我检查ArrayList.contains(value)方法中是否包含一个元素,并且要打印是否存在,我没有输出。 I am wondering why as the list.contains("Red") method should return TRUE . 我想知道为什么list.contains("Red")方法应该返回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). 当JVM开始执行Java程序时,它会搜索具有此签名的main方法(即String数组)。

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 使用public class MyClass代替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. 使用以下代码,它在我的本地环境中有效,您的代码中缺少一些内容,缺少了修饰符,并且没有“ String [] args ”。此外,我对代码进行了一些重构。 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);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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