gpt4 book ai didi

java - 封装数组索引偏移访问的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-02 04:55:56 26 4
gpt4 key购买 nike

为了对大量计算进行建模,我需要将速度与代码编写者和读者的一些便利结合起来。

第一个重要部分是计算和存储按出生年份、性别、年龄等索引的数据。

例如,我的出生年份范围是从 1900 到 2050。因为我无法声明从 1950 到 2050 的非零索引数组,所以我想封装从 [0..150] 到 [1900.. 2050]。显然,它更不容易出错,并且更容易阅读和编写代码,例如

valueArray.setValue(1950, someValue);

valueArray[1950 - 1900] = someValue;

如果您必须使用多个不同的数组范围执行数百次。

速度对于我的任务至关重要。所以我想知道是否有一种比下面所示的对我来说显而易见的方法更好更快的方法。您是否会采取完全不同的方法来解决这个问题?

public class OffsetArray {

private int min;
private int max;
private double initValue;
private double[] values;

public OffsetArray( int min, int max, double initValue ) {
this.min = min;
this.max = max;
this.values = new double[max-min+1];
this.initValue = initValue;
this.init();
}

private void init() {
for ( int i = 0; i<max-min+1;i++) {
values[i] = this.initValue;
}
}

public double getValue(int index) {
return values[index-min];
}

public void setValue(int index, double value ) {
this.values[index-min] = value;
}

public int getMin() {
return min;
}

public int getMax() {
return max;
}

编辑的附加要求:

我需要这种具有多个维度且范围以负数开头的数组,即 [-50..50]。

最佳答案

为什么不使用 HashMap?它们非常高效,让您可以根据键“索引”。

      Map<String, List<Integer>> map = new HashMap<>();
map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(10);
map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(20);
map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(30);

System.out.println(map.get("1900-2000"));

您可以使用某种方法根据相关值(对象)的状态创建键。

关于java - 封装数组索引偏移访问的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410981/

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