Printing out the elements in a ArrayList | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Printing out the elements in a ArrayList

I'm having trouble printing out the elements in this ArrayList it print out this e.g: rpg.Berserker@4e25154f, when I just want Berserker. public void playRound() { //have each contestant deal damage and take, and print description for (int i = 0; i < c.size(); i++){ String display = Arrays.toString(c.toArray()); //Need to print who is taking damage System.out.println(c.get(i) + " takes (" + c.get(i).attack(c) + ") damage"); }

20th Apr 2019, 5:19 AM
Les.lie
1 Answer
+ 2
Your problem is with something known as "implicit string conversion". In general, implicit conversion occurs when a variable is automatically converted from one type to another type. For example: int i = 5; double d = 4.34 + i; Here, we are allowed to add "i" to 4.34 (a double), because variables of type int can be implicitly converted to type double. This is as opposed to explicit conversion, where you need to use casting or call a method to convert the variable's type. Such as String-to-int conversions: String str = "35"; int i = 9 + Integer.parseInt(str); We need to explicitly call "Integer.parseInt" in order to convert the string to an int; hence, explicit conversion. As it turns out, in Java, all objects can be implicitly converted to Strings. This is why you can call System.out.println() on any object, even if you haven't defined an overload for that object's class. But how does Java know how to convert the object into a String? Well, if the object has a defined "toString()" method, then it just uses that. Otherwise, it makes a string with the object's class, followed by the '@' sign, followed by the object's memory address (in hexadecimal). It will look something like this: > my.class.Name@12345678 You can change this by defining the toString() method. Like so: class Person { int age; String name; ... String toString() { return (name + " is " + age + " years old"); } } Then I can call: Person p = new Person("George", 28); System.out.print(p); //output: "George is 28 years old" When you print c.get(i) + "...", it automatically tries to convert the result of c.get(), which is of type Berserker, into a String. Since the Berserker class does not have a defined toString() method, it uses the default format. This is why it outputs all of that weird crap. To fix this problem, you might want to try to define a toString method in the Berserker class: class Berserker { ... String toString() { return "Berserker"; } }
20th Apr 2019, 4:05 PM
Jack McCarthy
Jack McCarthy - avatar