for
是否可以使用指令在接口中初始化数组?
问问题
2293 次
5 回答
6
简单的问题 - 是否可以在界面中初始化数组?
是的。
这可行,但我想通过“for”指令初始化数组。好的,谢谢帮助
这不是一个简单的问题;)
您不能严格执行此操作,因为您不能将静态块添加到接口。但是你可以有一个嵌套的class
or enum
。
恕我直言,这可能比有用的更令人困惑,如下所示:
public interface I {
int[] values = Init.getValue();
enum Init {;
static int[] getValue() {
int[] arr = new int[5];
for(int i=0;i<arr.length;i++)
arr[i] = i * i;
return arr;
}
}
}
于 2012-08-14T08:28:52.350 回答
4
你为什么不试试看呢?
public interface Example {
int[] values = { 2, 3, 5, 7, 11 };
}
于 2012-08-14T08:05:52.547 回答
2
是的,但前提是它是静态的。事实上,在接口中声明的任何变量都将自动是静态的。
public interface ITest {
public static String[] test = {"1", "2"}; // this is ok
public String[] test2 = {"1", "2"}; // also ok, but will be silently converted to static by the compiler
}
但是你不能有静态初始化器。
public interface ITest {
public static String[] test;
static {
// this is not OK. No static initializers allowed in interfaces.
}
}
显然,接口中不能有构造函数。
于 2012-08-14T08:11:54.027 回答
2
是的,这是可能的。见代码:
public interface Test {
int[] a= {1,2,3};
}
public class Main {
public static void main(String[] args) {
int i1 = Test.a[0];
System.out.println(i1);
}
}
于 2012-08-14T08:17:01.087 回答
1
Firstly, I agreed with existing answers.
Further, I don’t think it’s a good idea to define data in an interface. See "Effective Java":
Item 19: Use interfaces only to define types
The constant interface pattern is a poor use of interface.
To export constants in interface is bad idea.
于 2012-08-14T09:02:43.233 回答