gpt4 book ai didi

Java数组:Java pass by reference and pass by value?

转载 作者:行者123 更新时间:2023-12-01 18:42:49 29 4
gpt4 key购买 nike

我正在尝试反转位图数组,而不修改源数组。但问题是源数组也被颠倒了。我做错了什么还是我应该以其他方式做?感谢您的帮助。

private GalleryAdapter galleryAdapter;
private ReverseGalleryAdapter rGalleryAdapter;

public void onCreate(Bundle savedInstanceState) {
galleryAdapter = new GalleryAdapter(this, imageThumbnails, imagePaths,
videoThumbnails, videoPaths);

imagegrid.setAdapter(galleryAdapter);

rGalleryAdapter = new ReverseGalleryAdapter(this, reverseBArray(videoThumbnails), reverseSArray(videoPaths),
reverseBArray(imageThumbnails), reverseSArray(imagePaths));

imagegrid2.setAdapter(rGalleryAdapter);
}

private Bitmap[] reverseBArray(Bitmap[] v){
Bitmap[] bTemp;
bTemp = v;
int len = bTemp.length;
Bitmap temp;
for (int i = 0; i < len/2; i++)
{
temp = bTemp[i];
bTemp[i] = bTemp[len-1 - i];
bTemp[len-1 - i] = temp;
}
return bTemp;
}

private String[] reverseSArray(String[] s){
String[] sTemp;
sTemp =s;
int len = sTemp.length;
String temp;
for (int i = 0; i < len/2; i++)
{
temp = sTemp[i];
sTemp[i] = sTemp[len-1 - i];
sTemp[len-1 - i] = temp;
}
return sTemp;
}

最佳答案

 Bitmap[] bTemp;
bTemp = v;

当您执行此操作时,肯定会引用同一个数组,因为您没有在那里创建新数组。

同样的情况也发生在这里

  String[] sTemp;
sTemp =s;

可能的解决方案:Make copy of array Java (建议阅读可能的方式后进行选择)。

我的建议来自Official docs :(参见复制数组部分)

The System class has an arraycopy() method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)

关于Java数组:Java pass by reference and pass by value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220152/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com