0

I've been given the following array

   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]);
     }
  }

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 :(

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58

3 Answers3

2

Override toString method in your Tests class ..

class Tests{

  ..... your code

  @Override
  public String toString(){
     ... return the value
  }
}
waelhe
  • 381
  • 2
  • 13
2

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.

The merit about overriding toString:

Help the programmer for logging and debugging of Java program

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 ;
  }
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
0

You need to override the toString() method in your tests class.

For further discussion, see How to use the toString method in Java?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012