【问题标题】:how do I call an object arraylist method from inside an external class如何从外部类内部调用对象数组列表方法
【发布时间】:2019-10-22 03:07:27
【问题描述】:

我想从一个外部类调用 theArrayList() 方法,该类显示名为 theList 的对象数组列表内的内容。我怎样才能做到这一点?

mendietaRAL.java

import java.util.ArrayList;

public class mendietaRAL {
  public static void theArrayList() {
    ArrayList<Object> theList = new ArrayList<Object>();

    theList.add(123);
    theList.add("Java");
    theList.add(3.75);
    theList.add("Summer C");
    theList.add(2018);

    for (int i = 0; i < theList.size(); i++) {
      System.out.print(theList.get(i));
    }

    theList.remove(1);
    theList.remove(4);

    for (int i = 0; i < theList.size(); i++) {
      System.out.print(theList.get(i));
    }
  }
}

mendietaRpgm2.java

public class mendietaRpgm2 {
  public static void main(String args[]) {

  }
}

【问题讨论】:

  • public static void main(String args[]) { mendietaRAL.theArrayList(); } ?
  • @lealceldeiro 当我尝试这种方法时,我得到这个:mendietaRpgm2.java:3: error: package com.something does not exist import com.something.mendietaRAL; ^ mendietaRpgm2.java:7: 错误: 找不到符号 mendietaRAL.theArrayList(); ^ 符号:变量 mendietaRAL 位置:类 mendietaRpgm2
  • 您只需将mendietaRAL 导入mendietaRpgm2 类。

标签: java arrays arraylist indexing methods


【解决方案1】:

你通过类名mendietaRAL(这应该以大写开头)和方法theArrayList....调用一个静态方法,所以你会这样做(见下文)......但请确保将该类大写名称,因为这使得 mendietaRAL 看起来是一个变量

import com.something.mendietaRAL;

public class mendietaRpgm2 {
    public static void main(String args[]) {
         mendietaRAL.theArrayList();
    }
}

【讨论】:

    【解决方案2】:
    public class mendietaRpgm2 {
      public static void main(String args[]) {
       mendietaRAL.theArrayList();
      }
    }
    

    请将您的班级名称更改为 MendietaRpgm2。查看命名约定here。 此外,删除未使用的 ArrayList 导入。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多