简体   繁体   English

如何显示 Arraylist 中随机元素的方法?

[英]How to display methods from a random element in Arraylist?

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.我知道如何从ArrayList获取随机元素,但我不知道如何也只显示 1 个元素的方法。 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.例如,我有两个子类,其中包含一些非常基本的方法(它们基本上只是打印一些东西),而ArrayList在超类中。

This is my code with the Cat and Dog being subclasses.这是我的代码,其中 Cat 和 Dog 是子类。 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.例如,如果程序选择 Dog,那么我只希望显示 Dog 的noise()furr()的结果。 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 ));

You're looping through all animals and calling Animal#noise and Animal#furr.你循环遍历所有动物并调用 Animal#noise 和 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.Animal超级 class 维护一个包含Animal引用的List时,你就打破了这个约定。 Instead, use a pattern like the service locator pattern to avoid this.相反,使用类似service locator pattern来避免这种情况。

int randomIndex = (int) (Math.random() * an.size());

Animal animal = an.get(randomIndex);

animal.noise();
animal.furr();

You can create a method for that after you select the random element pass it to a method then print it.您可以在 select 之后创建一个方法,将随机元素传递给一个方法然后打印它。 I find it for you.我给你找。

public int getRandomElement(List<Integer> list) 
{ 
    Random rand = new Random(); 
    return list.get(rand.nextInt(list.size())); 
}

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

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