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.

3
  • 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. Commented Nov 20, 2020 at 9: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() Commented Nov 20, 2020 at 14:17
  • I tried that as well but it didn't work. Do you have another kind of solution? Commented Nov 20, 2020 at 16:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried that as well but it didn't work. Do you have another kind of solution?
can you provide more information about why it's not working? what is the output you are getting exactly?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.