【问题标题】:why can't we add elements to ArrayList outside of the main() method?为什么我们不能在 main() 方法之外向 ArrayList 添加元素?
【发布时间】:2016-04-21 03:37:24
【问题描述】:
public class first {

    ArrayList<String> al= new ArrayList<String>();
    al.add("Batman");          //it doesn't work
    public static void main(String[] args) {

    }
}

为什么不允许在 main 之外使用 add 方法?

【问题讨论】:

标签: java arraylist


【解决方案1】:

你缺少括号。

试试这个代码:

public class first {

    ArrayList<String> al= new ArrayList<String>();
    {
          al.add("Batman");  
    }        

    public static void main(String[] args) {

    }
}

【讨论】:

    【解决方案2】:

    我不知道为什么 Java 语言的创建者会得出他们所做的结论,所以很遗憾我能给出的最佳答案是:无法做到,因为 Java 语言(编译器)不允许你这样做.

    可以做的就是将该方法调用用大括号括起来,然后它变成initializer block

    这是一个类似的问题:Why is this Java code in curly braces ({}) outside of a method?

    【讨论】:

      【解决方案3】:

      它是Java的一个基本概念或Java的体系结构,你只能在类中声明变量和方法。所有与功能相关的工作都应仅在功能中完成。

      类定义可以参考这个链接http://www.tutorialspoint.com/java/java_object_classes.htm

      【讨论】:

        【解决方案4】:

        class 具有以下结构:attributes(您的arraylist)后跟functions(如main())。

        要对attribute 进行任何操作,必须在function 内进行。这样做是因为它是这样设计的。

        【讨论】:

          【解决方案5】:

          “al”是“first”类的实例变量,如果不声明“first”类的对象,您甚至无法在主函数中添加任何内容。

          如果您必须在 main 函数之外添加任何内容而不创建类对象,则该实例必须是静态的,然后您可以通过将其放在花括号内来添加字符串。

          ArrayList<String> al = new ArrayList<>();
          
          {
              al.add("names");
          }
          

          【讨论】:

            【解决方案6】:

            factory methodfluent builder 等模式在不存在构造函数的情况下在 java 中会非常有用,因为它们允许您在同一个表达式中声明、实例化和初始化对象.

            以下是您的案例:

            List<String> l = java.util.Arrays.asList("Batman");
            
            ArrayList<String> al = new ArrayList<String>(java.util.Arrays.asList("Batman"));
            
            ArrayList<String> al = com.google.common.collect.Lists.newArrayList("Batman");
            

            最后一个示例使用Guava 库。它具有适用于所有类型的 java 集合的工厂方法和/或构建器。

            【讨论】:

              【解决方案7】:

              根据 Java 架构,您不能在方法之外编写任何逻辑语句 .

              【讨论】:

                猜你喜欢
                • 2012-06-21
                • 2014-09-01
                • 1970-01-01
                • 2014-10-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多