【问题标题】:In java, is there anyway to go from a array of objects that got returned to the number of objects in the array? [closed]在java中,是否有从返回的对象数组到数组中对象的数量? [关闭]
【发布时间】:2012-07-19 02:53:55
【问题描述】:

换句话说,我得到 {b,b,b} 我想要 3。我正在尝试复制康威的生命游戏,我希望单元格返回相邻单元格的数量。现在它所做的只是找出它附近是否有物体,如果有的话,它将它们存储在一个假想的盒子里,你如何让它把盒子里的物体数量转换为整数。

编辑:我发现它作为列表返回,得到它,所以编译器没有注意到任何错误,但是当我运行它时,我得到了这个。

java.lang.ClassCastException: java.util.ArrayList cannot be cast to Cell at Cell.lookForCells(Cell.java:33) at Cell.act(Cell.java:24) at greenfoot.core.Simulation.actActor(Simulation.java:507) at greenfoot.core.Simulation.runOneLoop(Simulation.java:470) at greenfoot.core.Simulation.runContent(Simulation.java:204) at greenfoot.core.Simulation.run(Simulation.java:194)

【问题讨论】:

  • 你学过Java语言吗?
  • 我用Greenfoot上了一堂课,这是一个简化版。

标签: java arrays integer greenfoot


【解决方案1】:

您需要使用方法size() 来获取列表中的对象数量:

List<String> list = new ArrayList<String>();
list.add("balh");
list.add("balh");
list.add("balh");
System.out.println(list.size());

输出:

3

对于对象数组,您需要使用最终字段length

String[] array = {"blah", "blah", "blah"};
System.out.println(array.length);

输出:

3

【讨论】:

    【解决方案2】:

    当然,简单:

    char[] array = {'b', 'b', 'b'};
    int num = array.length;
    

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多