计算ArrayList中不同对象类型的数量

时间:2015-12-09 04:00:42

标签: java arraylist counting

对于这个程序,我有一个动物的arraylist充满了来自两个子类的对象(Fish和Tiger类)我很难弄清楚如何计算每个项目类型,以便我可以打印出来。我需要它说像有3只老虎和2条鱼。 这是我到目前为止的代码

import java.util.*;
public class Menagerie{
   public static void main(String [] args){
      /* ArrayList to hold animal data */
      ArrayList<Animal> alist = new ArrayList<Animal>();
      /* object creations */
      Tiger jtiger = new Tiger("Javan Tiger", "Tiger acreage #6");
      Fish fnfish = new Fish("False network catfish", "Fresh Water");
      Tiger btiger = new Tiger("Bengal tiger", "Ritchie area of RIT");
      Fish shark = new Fish("Shark", "Salt Water");
      Tiger stiger = new Tiger("Siberian Tiger", "Tiger acreage #4");

      /* Adding objects to alist ArrayList */

      alist.add(jtiger);
      alist.add(fnfish);
      alist.add(btiger);
      alist.add(shark);
      alist.add(stiger);

      /* printing out animal information using toString() */

      System.out.println("Report on animals...");
      System.out.println(jtiger.toString());
      System.out.println(fnfish.toString());
      System.out.println(btiger.toString());
      System.out.println(shark.toString());
      System.out.println(stiger.toString());





   }


}

任何帮助都会很棒!感谢。

4 个答案:

答案 0 :(得分:3)

1。)迭代alist

for(Animal animal : alist){

}

2。)有两个计数器,一个用于tigerCount,另一个用于fishCount

3.。)相应地检查instanceOf classincrement

  for(Animal animal : alist){
        if(animal instanceOf Fish){
              fishCount++;

         }else if(animal instanceOf Tiger){
             tigerCount++;
         }
    }

instanceof keyword是一个二元运算符,用于测试对象(实例)是否是给定Type的子类型。

  

instanceof 运算符用于在运行时检查对象的类型。   它是程序获取运行时类型的方法   有关对象的信息。 instanceof运算符也很重要   在运行时转换对象的情况。 instanceof运算符返回布尔值   value,如果对象引用是指定类型,则返回 true   否则错误

答案 1 :(得分:0)

我创建了一个最小的可编译示例,因此它不使用您预先存在的类。

public class Main {
    public static void main(String... args) {
        List<Animal> animals = new ArrayList<Animal>();

        //create animals
        for (int i = 0; i < 5; i++)
            animals.add(new Dog());
        for (int i = 0; i < 3; i++)
            animals.add(new Cat());
        for (int i = 0; i < 8; i++)
            animals.add(new Cow());

        //create HashMap with class type as key
        Map<String, Integer> types = new HashMap<>();

        for (Animal a : animals) {
            Integer count = types.get(a.getClass().getSimpleName());
            //if count is null then we need to create a new entry with the value of 1
            //otherwise just increase count and replace
            types.put(a.getClass().getSimpleName(), count == null ? 1 : ++count);
        }

        //go through each entry and print it out
        for(Map.Entry<String, Integer> x : types.entrySet()){
            System.out.println(x.getKey() + " -> Total " + x.getValue());
        }
    }

    //ignore static. just because i'm using main method
    static class Animal{}
    static class Dog extends Animal{}
    static class Cat extends Animal{}
    static class Cow extends Animal{}

}

答案 2 :(得分:0)

更通用的解决方案是:

// Map captures {Type => #Animals}
Map<String,Integer> animalCount = new HashMap<>();
for( Animal animal : alist )
  {
    String className = animal.getClass().getName();
    Integer count = animalCount.get( className );
    if( count == null )
      {
        // First time we've seen this type of Animal
        animalCount.put( className, 1 );
      }
    else
      {
        // We've seen this type of Animal at least once
        animalCount.put( className, count + 1 );
      }
  }

// Print out a series of lines like "There were 7 Tiger(s)"
for( Map.Entry<String,Integer> reportRow : animalCount.entrySet() )
  {
    System.out.println( "There were "+reportRow.getValue() + " " + reportRow.getKey()+"(s)" );
  }

答案 3 :(得分:0)

如果您愿意,可以使用Java8版本

    Map<Class<? extends Animal>, List<Animal>> counted = alist.stream().collect(Collectors.groupingBy(anmial -> {
        if (anmial instanceof Tiger) return Tiger.class;
        if (anmial instanceof Fish) return Fish.class;
        return null;
    }));

    System.out.println(MessageFormat.format("There are {0} tigers and {1} fishes", counted.get(Tiger.class).size(), counted.get(Fish.class).size()));

查看java文档以获取更多详细信息:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html