How to Initialize an Array of Objects in Java

How to initialize an array of objects in Java

It is almost fine. Just have:

Player[] thePlayers = new Player[playerCount + 1];

And let the loop be:

for(int i = 0; i < thePlayers.length; i++)

And note that java convention dictates that names of methods and variables should start with lower-case.

Update: put your method within the class body.

Initializing array of objects in Java

You need to allocate space for the array itself, then initialize them elements.

Test[] t = new Test[20];
for (i = 0; i < 20; i++) {
t[i] = new Test(10, 20);
}

If the array's length is variable, you can just pass the value like you would any other variable.

int arraySize = 35;
Test[] t = new Test[arraySize];
for (i = 0; i < arraySize; i++) {
t[i] = new Test(10, 20);
}

Array size is fixed once you initialize it, but you can always get the array's length using the arr.length property.

How to initialize array of custom class objects?

There is some ways to do it:

Transforminfo[] somedamn = 
new Transforminfo[] { new Transforminfo(1,2,3,4,5),
new Transforminfo(6,4,3,5,6) };
Transforminfo[] somedamn =
{ new Transforminfo(1,2,3,4,5), new Transforminfo(6,4,3,5,6) };

First you create Transforminfo array link, then add new Transforminfo elements into.

It's like Integer []array = {1, 2, 3}, but you have to use constructor to create Transforminfo elements.

One more example to understand array of object creating. All way is equal.

String array[] = { new String("str1"), new String("str2") };
String[] array = { new String("str1"), new String("str2") };
String array[] = new String[] { new String("str1"), new String("str2") };
String[] array = new String[] { new String("str1"), new String("str2") };

How to initialize an array of objects and pass an array of strings?

There are a couple of problems with your code. But the most significant one is how in every class other than the one with main, you really have not declared any variable that belongs to the class. Do not introduce the class variables inside the constructors. Declare them outside the constructor so they can be global variables. Try:

public class qwixx {

player[] Players; //declared before using it in any methods / constructor

public qwixx(String[] players) {
Players = new player[players.length]; //value initialized inside the constructor
for (int x = 0; x < players.length; x++) {
Players[x] = new player(players[x]);
}
}

public void play() {
for (int i = 0; i < Players.length; i++) {
System.out.println(Players[i].getName());
}
}
}

Similarly, try doing the same in your player class:

public class player {

String name;

public player(String playerName) {
name = playerName;
}

public String getName() {
return name;
}

}

And on your main, you forgot to declare numPlayers as int. Do that too.

int numPlayers = input_scanner.nextInt

Java Object Array Initialization

You simply need to initialise the array. This can be done in the world constructor.

public world()
{

for (int i = 0; i < 4; i++)
{
ObArray[i] = new entity();
}

}

Then you can access the objects in your draw method, as you've shown:

public void draw()
{
for (int i = 0; i < 4; i++)
{
int x = ObArray[i].getXCoor();
int y = ObArray[i].getYCoor();

System.out.println("x" + x);
System.out.println("y" + y);

// Manipulate items in the array
// ObArray[i].setXCoor(10);
}
}

A more complete example, with the move functions added, and the class names capitalised:

public class Entity
{

private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;

public Entity()
{
xcoordinate = 20;
ycoordinate = 30;
}

private Entity(int newxcoor, int newycoor, String newname, char newsymbol)
{
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}

public int getXCoor()
{
return xcoordinate;
}

public void setXCoor(int xcoordinate)
{
this.xcoordinate = xcoordinate;
}

public int getYCoor()
{
return ycoordinate;
}

public void setYcoor(int ycoordinate)
{
this.ycoordinate = ycoordinate;
}

public static void main(String[] args)
{
World worldob = new World();

worldob.draw();

worldob.move(0, 15, 30);
worldob.move(1, 45, 0);
worldob.move(2, 23, 27);
worldob.move(3, 72, 80);

worldob.draw();
}

}

class World
{

private final Entity[] ObArray;

public World()
{
this.ObArray = new Entity[4];

for (int i = 0; i < ObArray.length; i++)
{
ObArray[i] = new Entity();
}

}

public void move(int index, int xCoor, int yCoor)
{
if (index >= 0 && index < ObArray.length)
{
Entity e = ObArray[index];
e.setXCoor(xCoor);
e.setYcoor(yCoor);
}
}

public void draw()
{
for (Entity e : ObArray)
{
int x = e.getXCoor();
int y = e.getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
}
}

}

How to initialize an array of objects?

This simply won't compile in Java (because you're assigning a value of an array type to a variable of a the non-array type Foo):

Foo foos = new Foo[12];

it's rejected by javac with the following error (See also: http://ideone.com/0jh9YE):

test.java:5: error: incompatible types
Foo foos = new Foo[12];

To have it compile, declare foo to be of type Foo[] and then just loop over it:

Foo[] foo = new Foo[12];  # <<<<<<<<<

for (int i = 0; i < 12; i += 1) {
foos[i] = new Foo();
}

Initializing an object in an array with a default value - java

The Java 8 way:

MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);

This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.

If you wanted to set some properties on the object or something, you could have a more involved supplier:

() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}

Constructors when creating a array of Objects

foos = new Foo[10];

creates an array that can hold references to 10 Foo instances. However, all the references are initialized to null.

You must call the constructor for each element of the array separately, at which point you can specify whatever argument you wish :

foos[0] = new Foo (...whatever arguments the constructor requires...);
...

How to initialize an array of objects within a constructor?

Your instance variable and local variable (in constructor) have the same name. Whenever you call the constructor the grid variable in the constructor is shadowing the instance variable. Remove the type declaration in your constructor, i.e. Location[][]

private Location[][] grid;


public Grid()
{
grid = new Location[10][10];
for(int i = 0; i < 10; i++)
{ .....


Related Topics



Leave a reply



Submit