[java] How to initialize an array of objects in Java

I want to initialize an array of Player objects for a BlackJack game. I've read a lot about various ways to initialize primitive objects like an array of ints or an array of strings but I cannot take the concept to what I am trying to do here (see below). I would like to return an array of initialized Player objects. The number of player objects to create is an integer for which I prompt the user. I was thinking the constructor could accept an integer value and name the player accordingly while initializing some member variables of the Player object. I think I am close but still quite confused too.

static class Player
{
    private String Name;
    private int handValue;
    private boolean BlackJack;
    private TheCard[] Hand;

    public Player(int i)
    {
        if (i == 0)
        {
            this.Name = "Dealer"; 
        }
        else
        {
            this.Name = "Player_" + String.valueOf(i);
        }
        this.handValue = 0;
        this.BlackJack = false;
        this.Hand = new TheCard[2];
    } 
}
private static Player[] InitializePlayers(int PlayerCount)
{ //The line below never completes after applying the suggested change
    Player[PlayerCount] thePlayers;
    for(int i = 0; i < PlayerCount + 1; i++)
    {
        thePlayers[i] = new Player(i);
    }
    return thePlayers;
}

EDIT - UPDATE: Here is what I am getting after changing this as I understood your suggestion:

Thread [main] (Suspended)   
    ClassNotFoundException(Throwable).<init>(String, Throwable) line: 217   
    ClassNotFoundException(Exception).<init>(String, Throwable) line: not available 
    ClassNotFoundException.<init>(String) line: not available   
    URLClassLoader$1.run() line: not available  
    AccessController.doPrivileged(PrivilegedExceptionAction<T>, AccessControlContext) line: not available [native method]   
    Launcher$ExtClassLoader(URLClassLoader).findClass(String) line: not available   
    Launcher$ExtClassLoader.findClass(String) line: not available   
    Launcher$ExtClassLoader(ClassLoader).loadClass(String, boolean) line: not available 
    Launcher$AppClassLoader(ClassLoader).loadClass(String, boolean) line: not available 
    Launcher$AppClassLoader.loadClass(String, boolean) line: not available  
    Launcher$AppClassLoader(ClassLoader).loadClass(String) line: not available  
    BlackJackCardGame.InitializePlayers(int) line: 30   
    BlackJackCardGame.main(String[]) line: 249  

This question is related to java arrays object initialization

The answer is


Arrays are not changeable after initialization. You have to give it a value, and that value is what that array length stays. You can create multiple arrays to contain certain parts of player information like their hand and such, and then create an arrayList to sort of shepherd those arrays.

Another point of contention I see, and I may be wrong about this, is the fact that your private Player[] InitializePlayers() is static where the class is now non-static. So:

private Player[] InitializePlayers(int playerCount)
{
 ...
}

My last point would be that you should probably have playerCount declared outside of the method that is going to change it so that the value that is set to it becomes the new value as well and it is not just tossed away at the end of the method's "scope."

Hope this helps


Instead of

Player[PlayerCount] thePlayers;

you want

Player[] thePlayers = new Player[PlayerCount];

and

for(int i = 0; i < PlayerCount ; i++)
{
    thePlayers[i] = new Player(i);
}
return thePlayers;

should return the array initialized with Player instances.

EDIT:

Do check out this table on wikipedia on naming conventions for java that is widely used.


thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

so the code line should be:

thePlayers[i] = new Player9();

If you can hard-code the number of players

Player[] thePlayers = {
    new Player(0),
    new Player(1),
    new Player(2),
    new Player(3)
};

If you are unsure of the size of the array or if it can change you can do this to have a static array.

ArrayList<Player> thePlayersList = new ArrayList<Player>(); 

thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g

Players[] thePlayers = thePlayersList.toArray();

Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization