只打印数组中的某些元素 [英] Print only certain elements in an Array

查看:71
本文介绍了只打印数组中的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下数组

   tests[] b = new tests[50];

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

So, there are some null elements in this array and I don't want to print those in my array.

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

所以,这会打印出@251970e2",但我需要能够打印出每个有效元素的内容,这些内容应该像蝙蝠侠"、小丑"、蝙蝠女"

So, this prints out '@251970e2' but I need to be able to print out each valid elements contents which should be like 'batman', 'joker', 'batgirl'

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

Sorry if this has been answered previously, I had a look but haven't had much luck :(

推荐答案

你需要在你的类中重写 toString 方法,因为它会以可读的格式为你提供关于对象的清晰信息可以理解.

You need to override toString method in your class because it is going to give you clear information about the object in readable format that you can understand.

覆盖toString的优点:

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

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

Since toString is defined in java.lang.Object and does not give valuable information, so it is good practice to override it for subclasses.

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

这篇关于只打印数组中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆