-1

How can I turn my Java Object to a string or something readable? I am struggling I tried 3 Methods that I found on SO.

System.out.println("tst: " + String.valueOf(alHolidays.get(dt)));
System.out.println("tst2: " + alHolidays.get(dt).toString());
System.out.println("tst3 " + "" + alHolidays.get(dt));

But the output is:

tst: [Ljava.lang.Object;@5217361e
tst2: [Ljava.lang.Object;@5217361e
tst3 [Ljava.lang.Object;@5217361e
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
yesIamFaded
  • 1,970
  • 2
  • 20
  • 45
  • Where can I put the overwrite toString? can it be placed above the sysout? – yesIamFaded Sep 08 '22 at 12:32
  • @yesIamFaded do you know what "to override" means in an OO environment? – Stultuske Sep 08 '22 at 12:38
  • I dont understand how to specify it for dt.. dt is just a for loop index and alHolidays is a ArrayList where .get(dt) it trying to get the element for that index – yesIamFaded Sep 08 '22 at 12:38
  • @yesIamFaded you don't. You create a "toString" method inside the class of which you are trying to print instances. If they are of type Object, you won't get any better. You'll need to cast them to the actual datatype – Stultuske Sep 08 '22 at 12:40
  • @Stultuske okay I dont really get that :D I just wanna look inside the object Java making me break my neck instead if just printing whats inside that. But anyways ty for the help maybe I will get the result somehow. – yesIamFaded Sep 08 '22 at 12:43
  • 2
    `System.out.println("tst3 " + Arrays.toString(alHolidays.get(dt)));` as the type is an array `[...`. Hopefully the array elements have a nice `toString()`. – Joop Eggen Sep 08 '22 at 12:45
  • 1
    @yesIamFaded actually, that is what is being showed. However, at the time you try to print it, it seems to be an instance of Object. Object is to abstract to know what you want to have printed, so it prints a default implementation. What you need to do is implement your own version of toString in your own class, and cast the result of a:Holidays.get(dt) to that datatype – Stultuske Sep 08 '22 at 12:46
  • @JoopEggen - that actually works I can see the data in there :D Honestly comming from JavaScript into Java is slowly killing me. – yesIamFaded Sep 08 '22 at 12:50
  • @yesIamFaded there are advantages too. – Joop Eggen Sep 08 '22 at 13:57

1 Answers1

0

If the object is an instance of a class that you created, override the toString() method on your class.

See https://www.baeldung.com/java-tostring for more details.

Riaan Nel
  • 2,425
  • 11
  • 18