我正在尝试构建一个自定义对象引用数组。这是一些简化的代码。
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对象的引用。
答案 0 :(得分:2)
您在每个城市存储相同的location
数组。为每个人制作一个新阵列,你应该很高兴。
for( int n = 0; n < nCities; n++ ) {
int[] location = new int[2];
location[0] = random.nextInt( this.dimension[0] );
答案 1 :(得分:0)
this.cities[n] = new City( diameter, location );
这是将同一个“位置”对象的参考分配给每个城市,因此最后当您打印所有城市时,它会将位置显示为最新的对象参考。
移动
int[] location = new int[2];
循环内的
for( int n = 0; n < nCities; n++ ) {
或只是
this.cities[n] = new City( diameter, new int[](random.nextInt( this.dimension[0] ),random.nextInt( this.dimension[1] ) );
答案 2 :(得分:-1)
在创建City对象时,您将相同的直径和位置传递给City构造函数,每次创建City对象时都需要找到一种方法来传递不同的直径和位置。
将不同的直径和位置存储在数组中,并在创建City Object时传递正确的值。