如何与特定的索引访问数组对象从一个不同的类在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

提供方法(s)为关联Animal[]Habitat

例如,如果你定义了一个接受Animal[]的构造函数,那么你可以先构建那个数组,然后把它传递给构造函数。您还可以提供一个设置器,允许您在任何时候交换到不同的Animal[]

public class Habitat {
private Animal[] animals; // note that this should be private
public Habitat(Animal[] animals) {
this.animals = animals;
}
public void setAnimals(Animal[] animals) {
this.animals = animals;
}
}

这允许main方法预先生成动物或在需要时分配它们。

public class Main {
public static void main(String[] args) {
Animal[] animals = ... build the array
Habitat habitat1 = new Habitat(animals);
Habitat habitat2 = new Habitat();
Animal[] moreAnimals = ... build another array of Animals
habitat2.setAnimals(moreAnimals);
}
}

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

…
habitat.addAnimal( this );
…

当然,这里假定Animal构造函数的第四个参数命名为habitat

并且animals属性不应该是数组,而应该是java.util.List的一个实例(最好是java.util.ArrayList)。然后这个新方法看起来像这样:

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

也许你必须添加一些检查(非空,例如),当你想确保一个动物只能添加一次时,你应该考虑使用java.util.Set而不是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;
}
}

仍然缺少错误处理。

相关内容