-2

I am trying to write an function incrList(L, x) that copies a given Linear Linked List, L, recursively and increment by a constant value, x. When I compile in terminal I got IntList@6ff3c5b5, which is a memory location, instead of the actual list. I only want to change the function incrList itself to give the right output.

public class IntList {
    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        first = f;
        rest = r;
    }
}

public class Lists1Exercises{

 
    public static IntList incrList(IntList L, int x) {
        if (L == null){
           return null;
        }else {
           IntList head = new IntList(L.first+x, null);
           head.rest = incrList(L.rest, x);
           return head;
        }
    }
public static void main(String[] args) {
        IntList L = new IntList(5, null);
        L.rest = new IntList(7, null);
        L.rest.rest = new IntList(9, null);


       
        System.out.println(incrList(L, 3));
    }
}
Kabocha Porter
  • 301
  • 3
  • 8
  • 1
    Does this answer your question? [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – Savior Jun 22 '20 at 23:30

2 Answers2

1

You need to override the toString method in your intlist class or write a method to convert from intlists to strings. You are returning an object, and by default they print as locations in memory.

0
public class IntList {
    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        first = f;
        rest = r;
    }

    @override
    public String toString() {
        // or whatever you want to print
        return "First: " + first + " | Rest: " + rest;
    }
}

By default the .toString() returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

But you can change it using @override and return whatever you want (usually something meaningful).

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43