我正在尝试构建自定义对象引用的数组。这是一些简化的代码。
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 对象的引用。
最佳答案
您在每个城市存储相同的location
数组。为每个数组创建一个新数组,然后就可以开始了。
for( int n = 0; n < nCities; n++ ) {
int[] location = new int[2];
location[0] = random.nextInt( this.dimension[0] );
关于Java:自定义对象引用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959582/