[英]How to Determine Frequency of String Array List Elements Using Classes in Java
对于Java代码,我有一个名为Animal的类,其中有变量+它们的获取器和设置器,例如名称和年龄。 main方法(在Launcher类中)允许用户使用addAnimal方法“放下”动物,并允许用户使用removeAnimal方法“拾起”动物。 有三种动物可以利用,每种动物都有各自的类别:狗,猫和鸟。 我希望能够计算每只动物的频率并将其显示为一个选项:“显示频率”,它将显示每只动物的频率,无论它们是否已“掉落”。
我在Collections Collections.frequency()
使用了静态频率方法。 我从Stack Overflow找到了这个,并认为它可以工作。 但是,每次添加狗,猫或鸟时,频率都保持为零。 我也尝试过使用Map<Animal, Long> counts = animals.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
这也没有提供我期望的输出。 它输出如下内容: Frequency of type 2 is {Cat@27d6c5e0=1, Bird@4f3f5b24=1}
,其中类型2为猫(选项2,我想让动物“下车”)。
下面是显示频率的代码。 我t really have a method for this, and I
不确定这是否会更方便。
ArrayList<Animal> animals = new ArrayList<>(); boolean addAnimal (int type, String name, int age) { //int frequency = Collections.frequency(animals, type); boolean isAdded = false; switch (type) { case 1: animals.add(new Dog(name, age)); isAdded = true; System.out.println("Frequency of " + type + ": "+ Collections.frequency(animals, (new Dog(name, age)))); case 2: animals.add(new Cat(name, age)); isAdded = true; System.out.println("Frequency of " + type + ": "+ Collections.frequency(animals, (new Cat(name, age)))); case 3: animals.add(new Bird(name, age)); isAdded = true; System.out.println("Frequency of " + type + ": "+ Collections.frequency(animals, (new Bird(name, age)))); default: isAdded = false; }//end of switch return isAdded; }//end of addAnimal(type, name, age) // here comes the method to remove an animal... }// end of class Database
我希望程序执行的操作是,当我选择显示每只动物的频率的选项时(假设这是选项3),我希望它输出“ Dog(类型1)的频率为3,因为有三只狗”,而猫(类型2)和鸟(类型3)的情况非常相似。 有没有一种简单的方法可以做到这一点? 我在Java Eclipse上编码。
这里的问题是每次调用函数时
Collections.frequency(animals, (new Dog(name, age)))
Collections.frequency检查动物是否有新创建的Object实例,该实例是唯一的。 因此,它将返回0。对于一个简单的解决方案,您可以为Animal类定义一个equals方法或创建另一个ArrayList例如
ArrayList<Integer> types =...
case 1:
animals.add(new Dog(name, age));
isAdded = true;
types.add(1);
您可以使用Collections.frequency()从中提取特定类型(1,2或3)的频率
(没有足够的声誉分数来发表评论,因此添加为答案)
您是否覆盖了Animal
的“等于”方法? 否则, Collections.frequency()
将始终为零,因为您每次都传递一个Animal
的new
实例来查找频率(使用默认equals
方法中的对象引用)。
我认为equals
和hashcode
在这种情况下无济于事,因为此方法看起来是实体的标识。 您不能选择所有使用它的狗。 我认为您需要使用类似于animals.stream().collect(Collectors.groupingBy(Animal::getClass, Collectors.counting()))
,但是这种解决方法不好(反射效果不好)。 可以使用数字,枚举等代替类,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.