【问题标题】:How to return Array List element from method如何从方法返回数组列表元素
【发布时间】:2015-07-20 16:27:51
【问题描述】:

我正在尝试将 CordsArray 的单个元素从公共类 Enemy() 传递到主类。

public class Enemy {

//constructor
public Enemy()
{
    //*create array of coordinates
    ArrayList<Integer> CordArray = new ArrayList<Integer>();

    CordArray.add(0,2);
    CordArray.add(1,5);
    CordArray.add(2,8);
    CordArray.add(3,10);
}

public static int returnCords(int[] CordArray, int index) 
{   
    return CordArray[index]; 
}

我想通过在 main 中调用 returnCords 将 CordArray 的元素输出到控制台:

System.out.println(returnCords(CordArray, 0));

但出现“CordArray 无法解析为变量”错误。抱歉英语不好。

【问题讨论】:

  • 查看您如何在Enemy 中定义变量CordArray 并查看returnCords 的arg 列表。当需要一个 int 数组时,您不能传递 ArrayList。
  • ChordArray 是构造函数中的一个局部变量,没有其他任何东西引用它,所以构造函数一退出它就不再存在。
  • 典型的rep-w***e诱饵问题

标签: java methods arraylist elements


【解决方案1】:

问题是:
- 变量名应以小写字母开头,
-lists 可以包含单个对象/值,您试图在一个索引中存储两个

改为创建 Coords 对象:

public class Coords{
    private int x;
    private int y;

    public Coords(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }
}

现在你可以这样做了:

ArrayList<Coords> cordArray = new ArrayList<Coords>();

希望对你有帮助。

【讨论】:

  • 他的代码比你列出的两个问题更多
  • 是的,CordsArray 的可见性,其他是我提到的两个结果。
【解决方案2】:

尝试通过 get 函数使用点和全局数组列表

import java.awt.Point;
import java.util.ArrayList;

public class Enemy {

    private final ArrayList<Point> points;

    public Enemy() {
        points = new ArrayList<>();
        points.add(new Point(2, 5));
        points.add(new Point(8, 10));
    }

    public ArrayList<Point> getPoints() {
        return points;
    }

    public static void main(String[] args) {
        Enemy enemy = new Enemy();
        int index = 0;
        Point point = enemy.getPoints().get(index);
        int x = point.x;
        int y = point.y;
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2018-10-15
    • 2019-10-25
    • 2020-12-31
    • 2021-11-25
    相关资源
    最近更新 更多