我想知道是否可以制作一个方法,该方法将某些东西的名称作为参数然后拼凑在一起。我们说我有三个arrays
:
arrayA,arrayB,arrayC。
所以,像这样:
public static void printArray(String id)
{
System.out.println("Array " + id + ": " + Arrays.toString(array + id) );
}
我希望在哪里跑步
printArray(C);
将(array + id)
转换为arrayC并打印arrayC的内容。不幸的是,它并没有,只是说" array"不是公认的符号。
我怎样才能做到这一点?
答案 0 :(得分:4)
可以使用reflection:
public class TestArray {
String[] arrayA = new String[] { "A content" };
String[] arrayB = new String[] { "B content" };
String[] arrayC = new String[] { "C content" };
public void printArray(String id) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
System.out.println("Array " + id + ": " + Arrays.toString((String[]) getClass().getDeclaredField("array" + id).get(this)));
}
public static void main(String[] args) throws Exception {
(new TestArray()).printArray("C"); // prints "Array C: [C content]"
}
}
但我认为这不是一个好主意,使用HashMap
可能是个更好的主意。
答案 1 :(得分:4)
恕我直言,你应该使用地图
String[] arrayA = {"a1", "a2", "a3"};
String[] arrayB = {"b1", "b2", "b3"};
String[] arrayC = {"c1", "c2", "c3"};
HashMap<String, String[]> mapArray = new HashMap<String, String[]>();
mapArray.put("A", arrayA);
mapArray.put("B", arrayB);
mapArray.put("C", arrayC);
当您想要检索数组时
public static void printArray(String id)
{
System.out.println("Array " + id + ": " + Arrays.toString(mapArray.get(id)));
}
答案 2 :(得分:0)
听起来你正在寻找reflection,但你无法反映局部变量,这听起来像是你想要的。
您最好的选择可能是调整printArray
以获取要转储其内容的数组:
public static void printArray(String id, Object[] array)
{
System.out.println("Array " + id + ": " + Arrays.toString(array) );
}
不幸的是,如果你想要一个通用的解决方案,你需要为每个基元类型重载:
public static void printArray(String id, boolean[] array){...}
public static void printArray(String id, char[] array){...}
public static void printArray(String id, double[] array){...}
...
您可以使用处理格式的private static
方法来保留解决方案DRY:
private static void outputArray( String arrayId, String arrayContents )
{
System.out.println("Array " + arrayId + ": " + arrayContents );
}
然后调整printArray
方法来调用它:
public static void printArray(String id, Object[] array)
{
outputArray(id, Arrays.toString(array) );
}
答案 3 :(得分:-1)
public static void printArray(String id)
{
System.out.println("Array " + id + ": content of Array" + id);
}
将完成这项工作。
在toString方法中,“array”是一个变量,之前没有声明它,因此你会得到错误信息。
编辑:
public static void printArray(String id){
if(id.equals("A")){
// print the content of array A
} else if(id.equals("B")){
// print the content of array B
} else if(id.equals("C")){
// print the content of array C
} else {
System.out.println("I don't know that array");
}
}
这就是你想要的吗?