1

I am having a problem regarding the printing of a special array:

I print an array of several objects with the System.out.println(Arrays.toString()); but now the array is filled with objects, that possess a value as char and I want to print each char assigned to the object. How can I do that in code?

To clarify, let the array be something specific like this:

Class[] objList = {new Class(1, 'X'), new Class(4, 'Y')};

Where I want to call the objList[0].toString() and then the objList[1].toString() method, getting an output looking like:

[X, Y]

I hope this question is clear enough and would be happy if anyone could help me, thanks!

NOTE: the mentioned Class with the toString() method is just implemented in the Class and is written as System.out.print(destination); I tried the explanation here: Use toString on array of objects, but apparently it did not work.

public String toString() {
  System.out.print(Arrays.toString(objList.toString()));
  return null;
}
Community
  • 1
  • 1
Maethor
  • 101
  • 3
  • 10
  • 1
    Sounds like you want [`Arrays.deepToString()`](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])) – dhke Dec 21 '16 at 19:07
  • @Maethor: Read the error; that takes an array, not a string. – SLaks Dec 21 '16 at 19:08
  • I tried this and only got: `The method deepToString(Object[]) in the type Arrays is not applicable for the arguments (String)` – Maethor Dec 21 '16 at 19:09
  • `Arrays.deepToString()` takes the array as an argument. Hence, call it without the intermediate `toString()`: `Arrays.deepToString(objList)`. – dhke Dec 21 '16 at 19:10
  • I see, now I get the `'X'` printed in front of the array which besides that consists of nulls – Maethor Dec 21 '16 at 19:12
  • You're returning `null` in `toString()`. Don't do any printing in the method; return the string that results from the `Arrays.deepToString` call. – TNT Dec 21 '16 at 19:22
  • Do not name custom types with the names of well-known standard types like `Class`. – Lew Bloch Dec 21 '16 at 19:49

1 Answers1

3

A toString() method is not supposed to print anything itself; instead, it should return a string which is a representation of the object. If your class's character is obtained through the getChar() method, you could implement its toString() method as follows:

public String toString() {
    return String.valueOf(getChar());
}

This will convert the character to a String and return it.

If you do that, the code

Class[] objList = new Class[] { new Class(1,'X'), new Class(2,'Y') };
System.out.println(Arrays.toString(objList));

should output [X, Y].

(I recommend to rename your class Class to something else, because it clashes with Java's Class<T> class.)

Hoopje
  • 12,677
  • 8
  • 34
  • 50