这是我的问题:
我想以一种非常清晰易读的方式创建一个数组,以便读者能够立即知道数组的元素。
当数组固定后,就很容易也很清楚了:
String[] columns = new String[] { "unit", "file_row", "unit_row", "content" };
String[] types = new String[] { "INTEGER", "INTEGER", "INTEGER", "TEXT" };
但我也有变量数组,具体取决于参数:
// Is an argument of my method, containing the variable elements of the future array
String[] method_arg = new String[] {"key1", "key2"};
// The clear and readable way doesn't work anymore
String[] columns = new String[] { "unit", method_arg, "hash"};
String[] types = new String[] { "INTEGER", method_arg_types, "INTEGER"};
// And the ways that work are ... much less readable
String[] columns = new String[] {"unit"};
columns = Stream.concat(Arrays.stream(columns), Arrays.stream(method_arg)).toArray(String[]::new);
columns = Stream.concat(Arrays.stream(columns), Arrays.stream(new String[] {"hash"})).toArray(String[]::new);
// Awkward
String[] types = new String[method_arg.length + 2];
Arrays.fill(types, "TEXT");
types[0] = "INTEGER";
如何使代码保持清晰易读? 代码相当灵活,使用列表应该不是问题,但我宁愿避免使用非标准库。 另外,我知道解决方案是创建一个方法来创建这些数组,例如
join_arrays(new String[] {"unit"}, method_arg, new String[] {"hash"});
但如果有解决方案使代码清晰并避免创建专用函数,那就更好了。如果没有,我将求助于这个选项。
谢谢,祝你有美好的一天!
最佳答案
我通常最终会使用自定义方法来解决此类问题:
private <T> T[] makeArray(T... elements) {
return elements;
}
您的示例如下所示:
String[] columns = makeArray("unit", method_arg, "hash");
String[] types = makeArray("INTEGER", method_arg_types, "INTEGER");
关于java - 如何以清晰易读的方式根据参数创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58008284/