首页 > 解决方案 > 如何从Java中的不同类访问具有特定索引的对象数组?

问题描述

我知道已经有很多类似于我的问题,但我仍然没有找到适用于我的问题的解决方案。我需要为此使用三个不同的类并给你一个想法,这是我的一些代码的样子(仅包括我认为相关的那些):

public class Main {
   //this is where I instantiate 
   public static void main(String[] args){
      Habitat habitat1 = new Habitat(some arguments/parameters here);
      Habitat habitat2 = new Habitat(some arguments/parameters here);

      Animal type1 = new Animal(some arguments/parameters here);
      Animal type2 = new Animal(some arguments/parameters here);
      Animal type3 = new Animal(some arguments/parameters here);
      Animal type4 = new Animal(some arguments/parameters here);
   }
}

public class Habitat {
   //other attributes here
   Animal[] animals;

   public Habitat(some arguments/parameters here) {

  //here I want to be able to reference/assign **Animal type1 and type2 to habitat1** and **Animal type3 and type4 to habitat2** 
}


public class Animal {
   //other attributes here
   Habitat habitat;
   
   public Animal(some arguments/parameters here){
    
   }

我知道为了拥有一组对象动物,我需要编写如下内容:

Animal[] animals = new Animal[4];

        animals[0] = type1;
        animals[1] = type2;
        animals[2] = type3;
        animals[3] = type4;
    

问题是我不能把这段代码放在类 Habitat 中,因为它不能访问 type1-type4。当我把它放在 Main 类中时,我无法在 Habitat 类中引用它。

基本上,我在这个特定问题中想要的具体输出是,例如,当我打印habitat1 的内容时,它看起来像这样:

Habitat 1 - Savanna
Mixed woodland-grassland
List of Animals: 
     Type 1
     Name: Tiger
     Diet: Carnivore

     Type 2
     Name: Elephant
     Diet: Herbivore

标签: javaarraysarraylist

解决方案


addAnimal( Animal animal )向这样的构造函数添加一个方法Habitat并调用它Animal

…
habitat.addAnimal( this );
…

当然,这假设Animal构造函数的第四个参数是 named habitat

并且animals属性不应该是一个数组,而是java.util.List(最好是 a java.util.ArrayList)的一个实例。然后新方法将如下所示:

public final void addAnimal( final Animal animal )
{
  animals.add( animal );
}

也许您必须添加一些检查(例如,非空),并且当您想确保只能添加​​一次动物时,您应该考虑使用java.util.Set而不是 a List(但这意味着对Animal类进行一些更改以及)。

如果您真的坚持属性的数组,则该addAnimal()方法会变得更加复杂:

public final void addAnimal( final Animal animal )
{
  if( animals == null )
  {
     animals = new Animals [1];
     animals [0] = animal;
  }
  else
  {
    var curLen = animals.length;
    var newAnimals = new Animal [curLen + 1];
    System.arraycopy( animals, 0 newAnimals, 0, curLen )
    animals = newAnimals;
    animals [curLen] = animal;
  }
}

或者

public final void addAnimal( final Animal animal )
{
  if( animals == null )
  {
     animals = new Animals [1];
     animals [0] = animal;
  }
  else
  {
    var curLen = animals.length;
    animals = Arrays.copyOf( animals, curLen + 1 );
    animals [curLen] = animal;
  }
}

仍然缺少错误处理。


推荐阅读