ArrayDeque 大小和内容

发布于 2024-11-19 12:35:01 字数 559 浏览 3 评论 0原文

我有以下代码。

    int clock;
    ArrayDeque<Integer> q = new ArrayDeque<Integer>();
    int customer = 1;
    Random r = new Random();

    for (clock = 0; clock <= 99; clock++) { 
        q.add(customer);
        customer++;
    }

根据我目前所知,它应该给我一个列表,或者在本例中是一个双端队列,大小为 100,有 100 个客户。

当我打印大小时,它验证了我的理论,但是当我打印内容时,它只返回索引 0-49。

    for (int i = 0; i < q.size() ; i++) {
        System.out.println("index "+ i + " "+ q.remove());
    }

打印 arraydeque 与打印其他 arraylist 不同吗?

I've got the following code.

    int clock;
    ArrayDeque<Integer> q = new ArrayDeque<Integer>();
    int customer = 1;
    Random r = new Random();

    for (clock = 0; clock <= 99; clock++) { 
        q.add(customer);
        customer++;
    }

Based on what I know so far it should give me a list, or in this case a deque, of size 100 with 100 customers.

When I print the size it validates my theory, however when I print the contents it only returns index 0-49.

    for (int i = 0; i < q.size() ; i++) {
        System.out.println("index "+ i + " "+ q.remove());
    }

Is printing arraydeque different from printing other arraylists?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃温暖了心ぐ 2024-11-26 12:35:01

问题是您与 q.size() 进行比较,它在每次迭代时都会减小。这是因为remove()实际上修改了队列。

您可以使用迭代器打印元素而不修改队列:

int i = 0;
for (int elem : q) {
    System.out.println("index "+ i++ + " "+ elem);
}

The problem is that you compare with q.size(), which decreases on each iteration. This is because remove() actually modified the queue.

You can print the elements without modifying the queue using the iterator:

int i = 0;
for (int elem : q) {
    System.out.println("index "+ i++ + " "+ elem);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文