我有:
byte[] AllNumber = {4,3,2,1,0,5,6,7,8,9};
byte[] MultNumber = {4,3,2,1,0,5,6,7,8,9}; // No matter the content
byte[] DivNumber = {4,3,2,1,0,5,6,7,8,9}; // No matter the content
Alter(AllNumber,MultNumber,DivNumber,5.0,3,2); //The Arrays must be Altered!!
for (int i = 0; i<MultNumber.length; i++) {
System.out.println("MultNumber["+i+"]:"+MultNumber[i]);
}
for (int i = 0; i<DivNumber.length; i++) {
System.out.println("DivNumber["+i+"]:"+DivNumber[i]);
}
现在我有这个方法:
Alter(byte[] src, byte[] Mlt, byte[] Dvs, double dNum, int Lngt, int Ini) {
// INI THE PROBLEM
Mlt = Arrays.copyOf(Mlt, src.length + Lngt); //HERE IS THE ASSIGNATION
for (int i = ini; i<Mlt.length; i++) {
Mlt[i] = Mlt[i]*dNum; //No matter the operation (to simplify the problem)
}
Dvs = Arrays.copyOf(Dvs, src.length - Lngt); //HERE IS THE ASSIGNATION
for (int i = Ini; i<Dvs.length; i++) {
Dvs[i] = Dvs[i]/dNum; //No matter the operation (to simplify the problem)
}
// END THE PROBLEM
}
再次尝试
//Another Attempt!!!
Alter(byte[] src, byte[] Mlt, byte[] Dvs, double dNum, int Lngt, int Ini) {
// INI THE PROBLEM
byte[] TM = new byte[src.length + Lngt]
for (int i = ini; i<Mlt.length; i++) {
TM[i] = Mlt[i]*dNum; //No matter the operation (to simplify the problem)
}
Mlt = TM; //HERE IS THE ASSIGNATION
TM = null;
byte[] TD = new byte[src.length - Lngt]
for (int i = Ini; i<Dvs.length; i++) {
TD[i] = Dvs[i]/dNum; //No matter the operation (to simplify the problem)
}
Dvs = TD; //HERE IS THE ASSIGNATION
TD = null;
// END THE PROBLEM
}
我想在调用“Alter”方法后更改两个安排。 我怎样才能做到这一点?
我需要更改数组的长度!
感谢您的宝贵帮助。
PD。似乎稍后对数组进行分配,“按引用调用”被转换为“按值调用”。如果省略 THE ASSIGNATION,则后面跟着“Call by Reference”。
最佳答案
I need to change the length of Arrays!
这在 Java 中是不可能的。您可以使用动态数据结构,例如 java.util.List 接口(interface)的实现。
您的分配没有帮助,因为方法参数是局部变量,引用原始对象。因此,您的对象有两个引用,并且您只需更改方法内已知的引用。
Java 使用按值调用,对于引用数据类型,该值是引用的值(因此您可以获得对同一对象的引用)。
当您想要更改数组时,您可以执行类似的操作。
public static int[] arrayTwiceAsBig(int[] original) {
int[] newOne = new int[original.length * 2);
System.arraycopy(original, 0, newOne, 0, original.length);
return newOne;
}
并这样调用它:
int[] myArray = {1,2,3};
myArray = arrayTwiceAsBig(myArray);
System.out.println(Arrays.toString(myArray));
关于java - 改变真实的字节数组Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804198/