【问题标题】:Correct ways to manipulate / get information from array of objects从对象数组中操作/获取信息的正确方法
【发布时间】:2013-11-02 08:40:03
【问题描述】:

我为类Plane 定义了一个对象数组。像这样:

        Plane[] terminalOne = new Plane[] {
            new Plane(1, "Madrid", "Ryanair", "Airbus A300", "05.00"),
            new Plane(3, "Riga", "AirBaltic", "Boeing 737", "05.30")
            //ETC..
        };

我试图弄清楚如何操作/从这个数组中获取信息,例如,显示对象。我试过System.out.println(terminalOne);,它返回[Lairport.Plane;@322ba3e4(机场是我的包裹)我不明白这是什么意思,但我认为它返回了第一个对象?我试图让它更具可读性,并在我定义平面类和对象构造函数的文件中添加了这个函数:

    public void displayPlane() // display plane
    { 
        System.out.println();
        System.out.print("{" + flightID + "," + destination + "," + airline + "," + aircraft + "," + time + "}");
        System.out.println();
    }

{.., .., .., .., ..} 的形式显示有关对象的信息并尝试在我的主文件中将其应用为terminalOne.displayPlane(); 但是编译器错误提示“找不到符号,符号:方法 displayPlane(),位置:变量终端之一类型平面[]"

我使用 LinkedLists 在单独的文件中定义了这些方法,以及搜索、删除等方法。我可以对数组执行类似的操作吗?如果可以,正确的方法是什么?

【问题讨论】:

    标签: java arrays object methods


    【解决方案1】:

    terminalOne 是一个数组,而不是一个单独的平面。你可以使用:

    for (Plane plane : terminalOne) {
        plane.displayPlane();
    }
    

    ...但我个人会考虑在Plane 中覆盖toString()

    @Override public String toString() {
        return "{" + flightID + "," + destination + "," + airline + "," +
               aircraft + "," + time + "}";
    }
    

    然后:

    for (Plane plane : terminalOne) {
        System.out.println(plane);
    }
    

    【讨论】:

    • 现在,我可以在我的 Plane 类中创建各种方法,然后以这种方式使用它们,对吗?另外,是否可以将此方法用于多个数组,例如for(Plane plane : terminalOne && terminalTwo)(试过了,不起作用)
    • @Ilja:不,您不能使用&& 来组合列表。但是你可以使用 Guava (guava-libraries.googlecode.com) 并使用 for (Plane plane : Iterables.concat(terminalOne, terminalTwo))
    【解决方案2】:

    正如 Jon 建议的那样,您可以将 displayPlane() 方法替换为 toString() 实现。
    然后你可以调用

    System.out.println("terminalOne = " + Arrays.toString(terminalOne));
    

    查看打印的数组的所有元素。

    要从“连接”输出结果,您可以这样做:
    :

    List<Plane> concatList = new ArrayList<Plane>();
    Collections.addAll(concatList, terminalOne);
    Collections.addAll(concatList, terminalTwo);
    // add many more terminals and then print
    System.out.println(concatList);
    

    仅使用标准 java 库

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 2019-09-12
      • 2016-08-10
      • 2021-03-18
      • 1970-01-01
      • 2022-10-02
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多