英文:
How to display methods from a random element in Arraylist?
问题
我知道如何从ArrayList
中获取随机元素,但我不知道如何仅显示一个元素的方法。例如,我有两个子类,其中包含一些非常基本的方法(它们基本上只是打印一些内容),而ArrayList
位于超类中。
这是我的代码,其中Cat和Dog是子类。现在,代码打印其中一个,但同时显示了两个类的方法。例如,如果程序选择了Dog,那么我希望仅显示Dog的noise()
和furr()
的结果。我应该如何做到这一点?
ArrayList<Animal> an = new ArrayList<>();
an.add(new Cat());
an.add(new Dog());
for (Animal a : an) {
a.noise();
a.furr();
}
int randomIndex = (int) (Math.random() * an.size());
System.out.println("The animal: " + an.get(randomIndex));
英文:
I know how to get a random element from ArrayList
, but what I don't know is how to also display only 1 element's methods. For example, I have two subclasses with a few methods that are very basic (they basically just print some stuff), and the ArrayList
is in the superclass.
This is my code with the Cat and Dog being subclasses. Now the code prints one of them but methods from both classes are displayed. If the program picks Dog for example, then I want only the results from Dog's noise()
and furr()
to be displayed. How could I do this?
ArrayList<Animal> an = new ArrayList<>();
an.add(new Cat());
an.add(new Dog());
for (Animal a : an) {
a.noise();
a.furr();
}
int randomIndex = (int) (Math.random() * an.size());
System.out.println( "The animal: " + an.get( randomIndex ));
</details>
# 答案1
**得分**: 1
你正在遍历所有动物并调用Animal#noise和Animal#furr。 相反,你想要做的是获取你选择的索引处的动物,并在该实例上调用这些方法。
值得一提的是,允许类具有多个职责是不常见的。 当Animal超类维护一个具有Animal引用的List时,会违反此约定。 相反,使用像“服务定位器模式”这样的模式来避免这种情况。
```java
int randomIndex = (int) (Math.random() * an.size());
Animal animal = an.get(randomIndex);
animal.noise();
animal.furr();
```
<details>
<summary>英文:</summary>
You're looping through all animals and calling Animal#noise and Animal#furr. What you want to do instead is get the animal at the index you've selected and call those methods on that one instance.
It's also worth mentioning that it's unconventional to allow classes to have more than one responsibility. When the `Animal` super class maintains a `List` with `Animal` references you break this convention. Instead, use a pattern like the `service locator pattern` to avoid this.
```java
int randomIndex = (int) (Math.random() * an.size());
Animal animal = an.get(randomIndex);
animal.noise();
animal.furr();
```
</details>
# 答案2
**得分**: 0
你可以在选择随机元素后创建一个方法,将其传递给一个方法然后打印它。我为你找到了代码。
```java
public int getRandomElement(List<Integer> list)
{
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
```
<details>
<summary>英文:</summary>
You can create a method for that after you select the random element pass it to a method then print it. I find it for you.
public int getRandomElement(List<Integer> list)
{
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论