在Java中循环打印ArrayList提供内存位置而不是字符串

时间:2016-10-11 17:57:29

标签: java arraylist tostring

对于我正在进行的项目,我必须实现一个基于文本的地图,玩家可以在其中导航,与地图上的某些对象进行交互。每次玩家(用户)拿起或放下一个物体时,都会(应该)显示玩家的库存,我已经写了以下代码:

ArrayList<GamePiece> inventory = new ArrayList<GamePiece>();

public String toString() {
    String result = "";
    for(int i = 0; i < inventory.size(); i++){
        result += " " + inventory.get(i);
    }
    return result;
}

我重写了toString方法,所以我可以打印出ArrayList中的元素,但每次我这样做只是打印内存位置。例如,如果我的库存中有Pebble和Stone,并且我调用此方法,则会返回以下内容:

[Pebble@75b84c92, Stone@6bc7c054]

我认为我在toString方法中做错了什么,我无法理解。如果你有任何想法,我很乐意听到他们,你对我的最后一个问题的帮助很大,所以我有信心!

这是我的Pebble课程:

public class Pebble extends Rock {
    private int pebbleWeight= 1;

    public Pebble() {
    }
    public char charRepresentation() {
        return 'P';
    }
    public String look() {
        return "This object is very small, with rounded edges and speckled with dark colors.";
    }

    public String touch() {
        return "Edges, shaped by millions of years of running water, are smooth.";
    }
    public int getWeight() {
        return pebbleWeight;
    }
    public String getName() {
        return "Pebble";
    }
}

这是Stone课程:

public class Stone extends Rock {
    private int stoneWeight = 4;
    public Stone() {

    }
    private int weight= 1;


    public char charRepresentation() {
        return 'S';
    }

    public String look() {
        return "This object is about the size of your fist, with rounded edges and dark colors.";
    }

    public String touch() {
        return "Edges, shaped by millions of years of running water, are smooth. Not too heavy...";
    }
    public int getWeight() {
        return stoneWeight;
    }
    public String getName() {
        return "Stone";
    }
}

摇滚课:

public class Rock extends GamePiece {

    public Rock() {
    }


    public String listen() {
        return "This object has no sound...";
    }

}

GamePiece类:

public class GamePiece {
    private int weight = 0;
    private int x = 0;
    private int y = 0;

    public GamePiece() {
    }
    public int getWeight() {
        return weight;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public char charRepresentation() {
        return '?';
    }
    public String look() {
        return "no description known";
    }
    public String listen() {
        return "no voice yet";
    }
    public String touch() {
        return "no texture yet";
    }
    public String getName() {
        // TODO Auto-generated method stub
        return null;
    }
}

0 个答案:

没有答案