简体   繁体   中英

Returning location not value

I have an ArrayList made up of objects from another class. I am having trouble accessing values from the ArrayList. I have populated my ArrayList, and have written the below to try and retrieve specific elements. However, I keep getting Player@4f2456 returned instead of the player's name.

public void playerName(int index)
{
    Player player = players.get(index);
    System.out.println(player);
}

I can return the list of players using this:

public void listAllPlayerNames()
{
    for (Player players : players)
        System.out.println (players.getPlayerName());
}

But can't ask for a specific playername to be returned.

You played yourself. :)

You're overloading two variables with the same name. I'm surprised the compiler doesn't warn you about this.

Instead of this:

for (Player players : players)
    System.out.println (players.getPlayerName());

This:

for (Player player : players)
    System.out.println (player.getPlayerName());

Also for this function:

public void playerName(int index)
{
    Player player = players.get(index);
    System.out.println(player);
}

You are printing the literal object identifier for "player" instead of the player's name. Isn't this what you want?

public void playerName(int index)
{
    Player player = players.get(index);
    System.out.println(player.getPlayerName());
}

This line will print your reference to your player object. That's why you get Player@4f2456 .

System.out.println(player);

This is the implementation of above method:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

So, in order to print player information correctly using System.out.println , you have to override the toString method in this class.

public class Player {
   @Override
   public String toString() {
       return playerName;
   }
}

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