英文:
How to set every item in the array A references to initialValue Java
问题
public static void initialize(int A[], int initialValue) { ; }
这是我代码的开始,我想知道怎样做可以使得运行后数组 A 中的每个项变为我设置的初始值。这是一个学校作业,教授告诉我们不能使用任何数组函数,所以不能用 arrays.func。
谢谢!
英文:
public static void initialize(int A[], int initialValue) { ; }
this is the start of my code, asking how you can make it so that after running, every item in the array A becomes what I made initialValue. It's for a school assignment and the professor told us we can't use anything with an arrays function so no arrays.func
Thanks!
答案1
得分: 5
你不需要那个方法。
只需调用:
Arrays.fill(A, initialValue);
顺便提一下,你的标题有一个错误。你的数组是一个基本类型数组,因此它不会包含对 initialValue 的引用,而是会包含多次那个 int 值。
英文:
You don't need that method.
Just call
Arrays.fill(A,initialValue);
BTW, your title has a mistake. Your array is a primitive array, so it won't contain references to initialValue, it will contain that int value multiple times.
答案2
得分: -1
这可以是另一种解决方案,
/*
 * 初始化数组的一小部分,并使用System.arraycopy调用以二进制扩展的方式填充数组的其余部分
 */
public static void initialize(int A[], int initialValue) { 
	
	int len = A.length;
	if (len > 0){
		A[0] = initialValue;
	}
	for (int i = 1; i < len; i += i) {
	   System.arraycopy(A, 0, A, i, ((len - i) < i) ? (len - i) : i);
	}
	
}
public static void main ( String [] args ) {
    int A[] = new int[5];
    initialize(A,1);
    for (int i : A) {
    	System.out.println(A[i]);
	} 
}   
输出:
1
1
1
1
1
英文:
This can be an another solution,
/*
 * initialize a smaller piece of the array and use the System.arraycopy 
 * call to fill in the rest of the array in an expanding binary fashion
 */
public static void initialize(int A[], int initialValue) { 
	
	int len = A.length;
	if (len > 0){
		A[0] = initialValue;
	}
	for (int i = 1; i < len; i += i) {
	   System.arraycopy(A, 0, A, i, ((len - i) < i) ? (len - i) : i);
	}
	
}
public static void main ( String [] args ) {
    int A[] = new int[5];
    initialize(A,1);
    for (int i : A) {
    	System.out.println(A[i]);
	} 
}   
OUTPUT:
1
1
1
1
1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论