gpt4 book ai didi

java - 如何在 Java 中保持列表索引固定

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:18 26 4
gpt4 key购买 nike

我想保持 Java 列表中项目的索引固定。

示例代码:

import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Double> a = new ArrayList<Double>();
a.add(12.3);
a.add(15.3);
a.add(17.3);

a.remove(1);
System.out.println(a.get(1));
}
}

这将输出 17.3。问题是 17.3 在索引 2 上,现在在索引 1 上!

有没有办法在删除元素时保留其他元素的索引?还是有其他类更适合这个目的?

注意:我不想要固定大小的集合。

最佳答案

您可能想使用 java.util.SortedMap使用 int 键:

import java.util.*;
public class Test {

public static void main(String[] args)
{
SortedMap<Integer, Double> a = new TreeMap<Integer, Double>();
a.put(0, 12.3);
a.put(1, 15.3);
a.put(2, 17.3);

System.out.println(a.get(1)); // prints 15.3
System.out.println(a.get(2)); // prints 17.3

a.remove(1);

System.out.println(a.get(1)); // prints null
System.out.println(a.get(2)); // prints 17.3
}
}
  • SortedMap 是一个可变大小的集合
  • 它存储映射到一组有序键的值(类似于 List 的索引)

没有实现java.util.List#remove(int)可能会保留索引,因为规范如下:

Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.

关于java - 如何在 Java 中保持列表索引固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com