Java – 打印队列的内容

huangapple go评论67阅读模式
英文:

Java - print contents of a queue

问题

你可以通过继承 Queue 类并覆盖 toString() 方法来获取正确的输出。以下是一个示例:

import java.util.LinkedList;
import java.util.Queue;

public class CustomQueue<E> extends LinkedList<E> {
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (E element : this) {
            sb.append(element.toString()).append(", ");
        }
        if (!isEmpty()) {
            sb.delete(sb.length() - 2, sb.length());
        }
        sb.append("]");
        return sb.toString();
    }

    public static void main(String[] args) {
        Queue<int[]> queue = new CustomQueue<>();
        int[] arr1 = {1, 2, 3};
        int[] arr2 = {4, 5, 6};
        queue.add(arr1);
        queue.add(arr2);
        System.out.println(queue.toString());
    }
}

这个示例中,我们创建了一个自定义的 CustomQueue 类,继承自 LinkedList,并覆盖了 toString() 方法以正确地输出队列中的元素。在 main 方法中,我们使用这个自定义队列来存储整数数组,并打印队列,会得到正确的输出。

英文:

I have a queue (where each element is an array of integer) defined as -

Queue&lt;int[]&gt; queue = new LinkedList&lt;&gt;();

When I try to print the queue, I get output like this as it prints the array object -

[[I@58d25a40]

How can I override the toString() method of Queue class to get the correct output ? I donot want to get the output by iterating over the queue. I hope to achieve it somehow by overriding the toString() method.

答案1

得分: 1

以下是翻译好的代码部分:

Queue<int[]> queue = new LinkedList<>() {
  @Override
  public String toString() {
    return "[" +
      stream()
      .map(Arrays::toString)
      .collect(Collectors.joining(", ")) +
      "]";
  }
};

queue.add(new int[] {1, 2});
queue.add(new int[] {3, 4});
System.out.println(queue);

打印输出:

[[1, 2], [3, 4]]

这应该是您想要的结果。

英文:

You can try something like this:

Queue&lt;int[]&gt; queue = new LinkedList&lt;&gt;() {
  @Override public String toString() {
    return &quot;[&quot; +
      stream()
      .map(Arrays::toString)
      .collect(Collectors.joining(&quot;, &quot;)) +
      &quot;]&quot;;
  }
};

queue.add(new int[] {1, 2});
queue.add(new int[] {3, 4});
System.out.println(queue);

printing:

[[1, 2], [3, 4]]

Which is presumably what you want.

This isn't necessarily a good idea. toString() should be used solely for debugging purposes: toString demands nothing of implementations, not even that they are consistent. Most things I can think of that would lead one to ask this question are problematic.

答案2

得分: 0

You can override the toString() method of the Queue interface by creating a custom class that implements Queue and extends a concrete class like LinkedList. Here's the relevant code:

import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ArrayQueue extends LinkedList<int[]> implements Queue<int[]> {

    @Override
    public String toString() {
        return this.stream()
            .map(Arrays::toString)
            .collect(Collectors.joining(", ", "[", "]"));
    }
}

And here's a test program:

import java.util.Queue;

public class ArrayQueueTest {
    public static void main(String args[]) {
        Queue<int[]> q = new ArrayQueue();
        q.add(new int[]{1, 2, 3});
        q.add(new int[]{4, 5, 6});
        q.add(new int[]{7, 8, 9});
        System.out.println(q);
    }
}

Running this code will yield the desired output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
英文:

> How can I override the toString() method of Queue class to get the correct output ?

You can't.

For starters, Queue is not a class, it's an interface. The concrete class you're using is LinkedList.

More concretely what you could do is defining a custom class that implements Queue and extends, for example LinkedList, and that class can have a custom toString method (see implementation below).

> I donot want to get the output by iterating over the queue. I hope to achieve it somehow by overriding the toString() method.

You'll have to iterate eventually, one way or another. You can just hide that iteration in another method, but the iteration will still be there under the hood.

Here's a quick blueprint of what you can do

import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ArrayQueue extends LinkedList&lt;int[]&gt; implements Queue&lt;int[]&gt; {

	@Override
	public String toString() {
		return this.stream()
			.map(Arrays::toString)
			.collect(Collectors.joining(&quot;, &quot;, &quot;[&quot;, &quot;]&quot;));
	}
}

And a test program

import java.util.Queue;

public class ArrayQueueTest {
	public static void main(String args[]) {
		Queue&lt;int[]&gt; q = new ArrayQueue();
		q.add(new int[]{1, 2, 3});
		q.add(new int[]{4, 5, 6});
		q.add(new int[]{7, 8, 9});
		System.out.println(q);
	}
}

Running this yields

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

huangapple
  • 本文由 发表于 2023年5月11日 16:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定