简体   繁体   中英

How to print an object from an object array in java?

This is an example of my object array.

Ball[] Array= {BallGrid[4], BallGrid[5]};

This is how I tried printing it out but the output was finalproject.Ball@1dcc2a3.

for(Ball value : Array){

    System.out.println(value);

}

How would I print out Array[0] so the value remains "BallGrid[4]"?

You have to override the toString() method in the class Ball :

@Override
public String toString() {
    ...
    return someStringHere;
}

where you return the String that you want to use to represent the ball.

Note: Assuming BallGrid is an array (because of BallGrid[4] ), you should call it ballGrid following Java naming conventions. And as @mikeyaworski commented, Array should be called array .

try this

    for (int i = 0; i < array.size() ;i++) {
        System.out.println(value.getClass().getSimpleName() + "[" + i + "]");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM