java - 如何从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
解决方案
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;
}
}
仍然缺少错误处理。
推荐阅读
- php - 禁用数据库缓存凭据 laravel
- python - 在“py”命令之后运行任意 Python
- python - 为什么我没有像我想的那样改变全局范围
- spring-boot - oauth2:resourceserver:jwt:jwk-set-uri for Azure b2c 在 Jhipster 中需要做哪些更改
- javascript - 从源代码/ iframe 模拟开发人员元素选择器?
- powershell - Abaqus 命令与 cmd 或 PowerShell 有何不同?
- python - 当用户访问我的网站而不是显示“页面正在建设中”时,我该怎么办?
- serverless - 飞行中的并发请求太多(计数:30,允许:30)
- matplotlib - 如何在 PyPlot 或 Matplotlib 中有效地重复部分情节以进行连续情节?
- python - 编写一个以正类为输入的混淆矩阵函数