繁体   English   中英

Java:自定义对象引用数组

[英]Java: Array of Custom Object References

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

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] );
        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] ) );

在创建City对象时,您要向City构造函数传递相同的直径和位置,因此您需要找到一种在每次创建City对象时传递不同的直径和位置的方法。

将不同的直径和位置存储在数组中,并在创建“城市对象”时传递适当的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM