【问题标题】:When do I have to import java.util.Arrays; when using Arrays我什么时候必须导入 java.util.Arrays;使用数组时
【发布时间】:2023-03-21 02:25:01
【问题描述】:

这是我项目的代码。

public class PhraseOMatic {
    public static void main(String[] args) {
        String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B",
        "win-win", "front-end", "web-based", "pervasive", "smart", "sixsigma”,"};
        String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented",
                "centric", "distributed", "clustered", "branded", "outsidethebox",
                "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared”"};
        String[] wordListThree = {"process", "tipping-point", "solution",
                        "architecture", "core competency”",
                        "portal", "space", "vision", "paradigm", "mission"};
        int oneLength = wordListOne.length;
        int twoLength = wordListTwo.length;
        int threeLength = wordListThree.length;
        int rand1 = (int) (Math.random() * oneLength);
        int rand2 = (int) (Math.random() * twoLength);
        int rand3 = (int) (Math.random() * threeLength);
        String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " +
                wordListThree[rand3];
        System.out.println("What we need is a " + phrase);
    }
}

它主要来自我的一位讲师。但我必须更改一些东西才能让它真正运行。

我的问题是,我什么时候必须导入 java.util.Arrays?即使我使用的是数组,它也无需导入即可运行。那么,这是为什么呢?

【问题讨论】:

  • 您在发布的代码中甚至在哪里使用数组?

标签: java arrays import


【解决方案1】:

只有在显式使用one of the methods that this class provides 时才需要导入java.util.Arrays。它所做的只是提供了处理数组的有用方法。如果你不调用它们中的任何一个,那么你也不需要导入它。

这有助于理解 Java 中的 import只不过是一种通过简单名称引用类的方式。换句话说,它允许您编写 Arrays.sort(someArray) 而不必键入 java.util.Arrays.sort(someArray)

【讨论】:

    【解决方案2】:

    数组java.util.Arrays不同。

    Java 语言有一个内置数组类型,您可以使用 String[]int[] 等表达式构造它。您无需声明任何内容即可使用它们。

    java.util.Arrays 不是这种对象的类型。它是一种工具类型,包含许多用于数组的方法:对它们进行排序、将它们转换为另一个集合等。如果你想使用这样的类,你需要使用 Fully Qualified Name 例如java.util.Arrays 或将其声明为 import java.util.Arrays 以便每次在课堂上需要它时只使用 Arrays 而不是 java.util.Arrays。后一种方法还可以使您的代码看起来更干净并节省一些输入。

    【讨论】:

      【解决方案3】:

      java.util.Arrays 是一个类。使用该类时需要导入该类。与所有其他类相同(java.lang 包中的类除外,它们是默认导入的)。在您的代码中,您没有使用 java.util.Arrays 类,因此您不需要导入它。

      【讨论】:

        【解决方案4】:

        您没有使用https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html 中的任何方法。这就是你不需要它的原因。

        [];% 等语言的一部分,这里定义为 https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.1

        在 Java 编程语言中,数组是对象(第 4.3.1 节),是 动态创建,并且可以分配给 Object 类型的变量 (§4.3.2)。 Object 类的所有方法都可以在数组上调用。

        【讨论】:

          猜你喜欢
          • 2013-04-30
          • 1970-01-01
          • 1970-01-01
          • 2014-11-08
          • 2013-10-23
          • 2016-10-22
          • 2020-03-06
          • 1970-01-01
          • 2011-03-18
          相关资源
          最近更新 更多