Java:自定义对象引用数组

标签 java arrays object reference

我正在尝试构建自定义对象引用的数组。这是一些简化的代码。

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/

相关文章:

java - 通用 War 文件就像 API 概念

java - 我的面向对象程序不会注册哨兵值并存在循环

c - 使用 sprintf 将字符串中的字符添加到其他字符串时出现意外输出

javascript - 如何从对象数组中获取 id 并创建数组

javascript set - 将值添加到集合内对象的数组中

javascript - 当调用 'this' 的函数位于子对象的对象内部时,您将如何引用 'this'?

java - 图书馆系统登录 退出

java - MapStruct 不复制子类属性

java - 尝试在 T 数组中使用二分搜索方法递归查找数字时出现 StackOverflowError

android - Arrayadapter.getcount 空点异常