Robery567 Robery567 - 5 months ago 41
Java Question

Implementing tail class

I am a beginner in Java and I have tried to implement a tail and I've made all the others methods, but at the toString() method, the program won't work.
Here's my attempt:

class Tail {
int n;
Node prim;
Node last;

class Node {
Node next;
int info;

Tail() {
prim = null;
last = null;
n = 0;

public String toString() {
StringBuilder s = new StringBuilder();
for (int info : this)
s.append(info + " ");
return s.toString();

It gives an error if I try to return .
I would appreciate any advice or solution for solving this problem, thanks


your code below is incorrect:

for (int info : this)
s.append(info + " ");

'this' refers to the current instance of Tail - which is all of its properties (n, prim, and last) & methods. If you want to overwrite toString() using the three properties refer to this answer for how to write your for loop:

How to get the fields in an Object via reflection?