可以通过使用循环遍历list中的元素,每次返回两个相邻的元素,如果list长度是奇数,则在最后一次循环时返回最后一位和第一位元素。

以下是示例代码:

List<Integer> list = new ArrayList<>();
// 添加元素
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

int index = 0;
while (index < list.size() - 1) {
    System.out.println(list.get(index) + ", " + list.get(index + 1));
    index += 2;
}

// 如果list长度是奇数,则返回最后一位和第一位元素
if (list.size() % 2 != 0) {
    System.out.println(list.get(list.size() - 1) + ", " + list.get(0));
}

输出结果为:

1, 2
3, 4
5, 1
``
java list如果存在两个以上两个元素如何每次请求时返回两个相邻的元素且list长度是奇数则可以返回最后一位和第一位元素

原文地址: http://www.cveoy.top/t/topic/ftlC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录