Я пытаюсь создать массив пользовательских ссылок на объекты.Вот упрощенный код:
import java.util.*;
public class Map {
private int[] dimension;
private City[] cities;
private int nCities;
public static void main( String[] args ) {
Map map = new Map( 5, 20, 500, 500 );
}
public Map( int nCities, int diameter, int w, int h ) {
this.dimension = new int[2];
this.dimension[0] = w;
this.dimension[1] = h;
this.create_cities( nCities, diameter );
}
private void create_cities( int nCities, int diameter ) {
// data
this.cities = new City[nCities];
this.nCities = nCities;
// locate cities
long seed = System.currentTimeMillis();
Random random = new Random( seed );
int[] location = new int[2];
for( int n = 0; n < nCities; n++ ) {
location[0] = random.nextInt( this.dimension[0] );
location[1] = random.nextInt( this.dimension[1] );
this.cities[n] = new City( diameter, location );
System.out.println( this.cities[n].toString() );
}
System.out.println( "\n" + Arrays.toString( this.cities ) );
}
}
Результат:
diameter: 20, location: [311, 324]
diameter: 20, location: [85, 294]
diameter: 20, location: [364, 182]
diameter: 20, location: [269, 412]
diameter: 20, location: [123, 200]
[diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200]]
Может кто-нибудь оторвать мою голову от стены?Я храню одну и ту же ссылку 5 раз, правильно?Как мне этого не делать?Я хотел бы сохранить ссылку на каждый уникальный объект City.