Displaying individual elements of an object in an Arraylist through a for loop?

45,802

Solution 1

You need to use index to access individual element: -

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

Then you can override toString() method in your Player class

public String toString() {
    return playerName + " : " + playerAge + " : " + playerPosition;
}

Solution 2

I can create the object and input it into the arraylist no problem using the case 2, but when I try to print it out I want to do something like

System.out.println("Player Name" + myPlayersArrayList.PlayerName + "Player Position" + myPlayerArrayList.PlayerPosition + "Player Age" + "Player Age");

I know that is not correct, but I dont really know what to do, if anyone can be of any help it would be greatly appreciated. Thanks


Just override toString() method to get desired output

Solution 3

You can also use forEach in Java 8:

List<String> myPlayersArrayList = new ArrayList<>();
myPlayersArrayList.stream().forEach((player) -> {
    System.out.println("Player: " + player); //Override toString() in Player class
});

Solution 4

A List is a collection of elements. The List provides a number of useful methods which allows you to manage it, add, remove, set, indexOf, contains and most importantly, in this case, get.

In order to manipulate a element within the list, you first need to "get" or retrieve it from the list.

List are Iterable, this means you don't need to use an indexed for loop to gain access to the various members (unless the index is of importance).

So you can do...

for(int i = 0; i < myPlayersArrayList.size(); i++){
    Player player = myPlayersArrayList.get(i);
    // display results
}

or

for (Player player : myPlayersArrayList) {
    // display results
}

To display the contents of the Player object you can do a number of different things...

You could simply display the various properties of the Player (I don't have access to your Player class, so I'm guessing at its properties)

System.out.println("Player Name: " + player.PlayerName + "; Player Position: " + player.PlayerPosition + "Player Age: " + player.PlayerAge);

Or you could write a "formatter" method. This could be static to the Player class or it could be part of utility class, depending on your needs

System.out.println(PlayerUtils.format(player)); // Format the player properties as you see fit

Or you can, as has already being suggest, override the toString method of the Player

System.out.println(player);

There are advantages and disadvantages to all these approaches.

I tend to like putting diagnostic information into my toString methods which isn't normally useful for displaying to the user. Formatters aren't always obvious to other developers (unless they are well documented ;)).

You will need to choose those which are most useful to you and your needs.

Share:
45,802
user1180888
Author by

user1180888

Updated on July 23, 2022

Comments

  • user1180888
    user1180888 almost 2 years

    I'm trying to Display individual elements of an Object I have created.

    It is a simple Java program that allows users to add and keep track of Player Details.

    I'm just stumped when it comes to displaying the details after they have been added already. here is what my code looks like

    I can create the object and input it into the arraylist no problem using the case 2, but when I try to print it out I want to do something like

    System.out.println("Player Name" + myPlayersArrayList.PlayerName + "Player Position" + myPlayerArrayList.PlayerPosition + "Player Age" + "Player Age");
    

    I know that is not correct, but I dont really know what to do, if anyone can be of any help it would be greatly appreciated. Thanks

    System.out.println("Welcome to the Football Player database");
     System.out.print(System.getProperty("line.separator"));
    
    
         UserInput myFirstUserInput = new UserInput();
        int selection;
                ArrayList<Player> myPlayersArrayList = new ArrayList<Player>();
    
                while (true) {
    
                    System.out.println("1. View The Players");
                    System.out.println("2. Add A Player");
                    System.out.println("3. Edit A Player");
                    System.out.println("4. Delete A Player");
                    System.out.println("5. Exit ") ;
                    System.out.print(System.getProperty("line.separator"));
    
                    selection = myFirstUserInput.getInt("Please select an option");
                    System.out.print(System.getProperty("line.separator"));
                    switch(selection){
    
    
            case 1: 
    
                            if (myPlayersArrayList.isEmpty())
                                        {
                            System.out.println("No Players Have Been Entered Yet");
                            System.out.print(System.getProperty("line.separator"));
                            break;}
    
                            else 
                            {for(int i = 0; i < myPlayersArrayList.size(); i++){
                                System.out.println(myPlayersArrayList);
    
            }
                        break;
    
                        case 2:  {
    
                            String playerName,playerPos;
                            int playerAge;
    
                                    playerName = (myFirstUserInput.getString("Enter Player name"));
                                    playerPos = (myFirstUserInput.getString("Enter Player Position"));
                                    playerAge = (myFirstUserInput.getInt("Enter Player Age"));   
    
                                    myPlayersArrayList.add(new Player(playerName, playerPos, playerAge));   ;
                                                            break;
                        }
    
  • user1180888
    user1180888 over 11 years
    Thanks for the reply, when i go to add [i] to the end though it says "array required, but ArrayList<Player> found".
  • user1180888
    user1180888 over 11 years
    Wow this worked brilliantly. How come it knows it is using the 'toString' method though? It doesnt look like it references it to me(?). Thanks!
  • Rohit Jain
    Rohit Jain over 11 years
    @user1180888 Ah! You need to do myPlayerList.get(i) to fetch, and myPlayerList.add() to add something..
  • imrandy85
    imrandy85 over 11 years
    When you put an object name inside of System.out.println() the toString() method is called automatically. You could also call object.toString() explicitly but as you've seen, that is not necessary.