java - 数组扩展/缩减
问题描述
我使用 Oracle JGeometry 方法,该方法返回(或作为方法参数)二维段作为双数组(x1,y1,x2,y2 ... xn,yn)。我想扩展这个数组以包含 3D 段作为双数组 (x1,y1,z1,x2,y2,z2 ... xn,yn,zn) 默认 Z 值或减少到 2D (通过删除所有 Z 坐标)。我编写了简单的实用方法来制作它。有没有更简单或更聪明的方法来做到这一点?
从 2D 到 3D 的转换:
public static double[] to3D(double z, double[] inputArray) {
List<Double> convertedItems = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
convertedItems.add(inputArray[i]);
if ((i + 1) % 2 == 0) {
convertedItems.add(z);
}
}
return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}
从 3D 到 2D 的转换:
public static double[] to2D(double[] inputArray) {
List<Double> convertedItems = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if ((i + 1) % 3 == 0) {
continue;
}
convertedItems.add(inputArray[i]);
}
return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}
解决方案
这应该会提供一些性能改进。
public static double[] to3D(double z, double[] inputArray) {
if (inputArray.length % 2 != 0) throw new IllegalArgumentException();
double[] convertedArray = new double[inputArray.length / 2 * 3];
for (int i = 0; i < inputArray.length / 2; i++) {
System.arraycopy(inputArray, i * 2, convertedArray, i * 3, 2);
convertedArray[i * 3 + 2] = z;
}
return convertedArray;
}
public static double[] to2D(double[] inputArray) {
if (inputArray.length % 3 != 0) throw new IllegalArgumentException();
double[] convertedArray = new double[inputArray.length / 3 * 2];
for (int i = 0; i < inputArray.length / 3; i++) {
System.arraycopy(inputArray, i * 3, convertedArray, i * 2, 2);
}
return convertedArray;
}
推荐阅读
- jquery - ajax function not working after adding async and await keywords
- python-3.x - Saving the content of large .txt file into variable in python
- symfony - Remember me works as if always_remember_me is set to true
- docker - Fluentd Failing to connect to ElasticSearch cluster
- sql - 如何在请求中正确使用预言机,“If”和“LIKE”条件
- vb.net - 加入两个 Sqlite 表时出现 Crystal Report 错误;数据库架构在“内部”附近发生了变化:语法错误?
- amazon-web-services - 如何在新机器上继续使用 Amplify?
- c - 如何从另一个标头数据访问匿名联合/结构成员?
- fancybox-3 - 在不同的视口宽度上显示不同的图像
- r - 如何使用 Sys.Date() 或 today() 将日期重新编码为 R 中的字符串或因子?