【问题标题】:Print only certain elements in an Array [duplicate]仅打印数组中的某些元素[重复]
【发布时间】:2014-12-08 19:33:32
【问题描述】:

我得到了以下数组

   tests[] b = new tests[50];

所以,这个数组中有一些空元素,我不想在我的数组中打印它们。

  for(int i = 0; i < b.length; i++){
     if(b[i] != null){
        System.out.println(b[i]);
     }
  }

所以,这会打印出“@251970e2”,但我需要能够打印出每个有效的元素内容,例如“蝙蝠侠”、“小丑”、“蝙蝠女”

对不起,如果之前已经回答过,我看了看,但运气不佳:(

【问题讨论】:

    标签: java arrays printing


    【解决方案1】:

    您需要在您的类中覆盖toString 方法,因为它将以您可以理解的可读格式为您提供有关对象的清晰信息。

    覆盖toString的优点:

    帮助程序员记录调试Java程序

    由于 toString 是在 java.lang.Object 中定义的,并没有给出有价值的信息,所以它是 为子类覆盖它的好习惯。

      @override
      public String toString(){
         // I assume name is the only field in class test
         return name ;
      }
    

    【讨论】:

    • +1 表示报价,应该是@Override
    【解决方案2】:

    在您的测试中覆盖toString 方法class ..

    class Tests{
    
      ..... your code
    
      @Override
      public String toString(){
         ... return the value
      }
    }
    

    【讨论】:

    • 我从来没有看到 toString 返回 void 。
    • 不打印,返回
    【解决方案3】:

    您需要覆盖 tests 类中的 toString() 方法。

    更多讨论请见How to use the toString method in Java?

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2021-05-03
      • 2012-06-09
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      相关资源
      最近更新 更多