0

I am trying to print the content of a PriorityQueue to an output file by converting it to an ArrayList.

(NOTE: I'm not printing to the console!)

Besides I declared a toString method, I am still getting the outputs like this: I@7c3df479

Converting the queue to ArrayList:

private PriorityQueue<GameState> unexpanded = new PriorityQueue<>(Comparator.comparing(GameState::getF_n));

...

public ArrayList<GameState> getUnexpanded()
    {
        ArrayList<GameState> unExpanded = new ArrayList<>(unexpanded);
        return unExpanded;
    }

Getting the ArrayList and trying it to print:

private void printSolution() throws IOException
    {
        FileWriter outFile = new FileWriter("output.txt");
        PrintWriter output = new PrintWriter(outFile);
        ArrayList<GameState> unexpanded = game.getUnexpanded();

        for (int i = 0; i < unexpanded.size(); i++)
        {
            output.printf(unexpanded.get(i).toString() + "\n");
        }

        output.close();
    }

toString method:

public class GameState
{
private int[][] grid;

...

@Override
    public String toString()
    {
        return "{" + grid + "}";
    }
}

Everything is working fine but the program print the contents like: I@7c3df479

Can anybody please help me with this?

Many thanks for the answers and comments in advance.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
PJacouF
  • 19
  • 8
  • My question closed stating that this question already have an answer but the linked question does not have an answer to my question. I request the reopening of my question. – PJacouF Nov 20 '20 at 09:29
  • The solution is the same: use `Arrays.deepToString(...)` to create a string representation of the 2D array. The fact that you need to use it in a `toString()` instead of printing its output to a console doesn't change the fundamental solution: use `Arrays.deepToString()` – Mark Rotteveel Nov 20 '20 at 14:17
  • I tried that as well but it didn't work. Do you have another kind of solution? – PJacouF Nov 20 '20 at 16:01

1 Answers1

1

'grid' is declared as a 2D array which isn't a primitive in java. As such, when you try to print it, it still prints out the memory address / reference.

Try replacing it with Arrays.deepToString(grid) instead.

jun
  • 192
  • 15
  • I tried that as well but it didn't work. Do you have another kind of solution? – PJacouF Nov 20 '20 at 16:01
  • can you provide more information about why it's not working? what is the output you are getting exactly? – jun Nov 20 '20 at 17:54
  • I don't know why it's not working that's why I asked. Output was the memory addresses, same as I stated in the question. – PJacouF Nov 21 '20 at 00:21