嘿,这段代码工作得很好,但很难阅读。我正在寻找一种更好的方法。
public void printArray(String[/*row*/][/*column*/] twoDiArray) {
if (twoDiArray.length == 2) {
for (int i = 0; i < twoDiArray[0].length; i++) {
//prints attribute name and value
attributeNameAndValue(twoDiArray[0][i],twoDiArray[1][i]);
}
} else {
System.out.println("Does not fit format standards :: 2d array :: two rows max :: first row name :: second row value");
}
}
我非常不喜欢的部分是 if 语句和 for 循环中的 length 调用。有没有更好的方法来做到这一点,或者这只是java语言的一个草率的部分。
最佳答案
您有名称-值对,如果您的名称是唯一的,您应该使用 Map<String, Integer>
反而。否则,创建您自己的类,例如Attribute
并使用List<Attribute>
:
public class Attribute {
private final String name;
private final int value;
public Attribute(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
这为您提供了第二维的编译时安全性。您的代码将如下所示:
public void printArray(List<Attribute> attributes) {
for (Attribute attribute : attributes) {
attributeNameAndValue(attribute.getName(), attribute.getValue());
}
}
关于java - 二维数组重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28947705/