Arrays 有没有办法将[indexOfMin]=a[startIndex]转换为ArrayList格式?我能';我似乎做得不恰当
在我的程序的底部,我试图将我的选择排序算法从数组转换为ArrayList。产生错误的那两行以前是Arrays 有没有办法将[indexOfMin]=a[startIndex]转换为ArrayList格式?我能';我似乎做得不恰当,arrays,arraylist,selection-sort,Arrays,Arraylist,Selection Sort,在我的程序的底部,我试图将我的选择排序算法从数组转换为ArrayList。产生错误的那两行以前是a[indexOfMin]=a[startIndex]和a[startIndex]=min。我试着把它们改成a.get(indexOfMin)=a.get(startIndex)和a.get(startIndex)=min但它不会编译。谢谢你的帮助 class SortDouble { public static void main(String[] args) { i
a[indexOfMin]=a[startIndex]代码>和a[startIndex]=min代码>。我试着把它们改成a.get(indexOfMin)=a.get(startIndex)代码>和a.get(startIndex)=min代码>但它不会编译。谢谢你的帮助
class SortDouble
{
public static void main(String[] args)
{
int n = 10;
ArrayList<Double> a = new ArrayList<Double>();
Random r = new Random();
for (int i = 0; i < n; i++)
a.add(r.nextDouble());
selectionSort(a);
for (int i = 0; i < n; i++)
System.out.println(a.get(i));
}
public static void selectionSort(ArrayList<Double> a)
{
int n = 10;
for (int startIndex = 0; startIndex < n - 1; startIndex++)
{
double min = a.get(startIndex);
int indexOfMin = startIndex;
for (int j = startIndex + 1; j < n; j++)
if (a.get(j) < min)
{
min = a.get(j);
indexOfMin = j;
}
a.get(indexOfMin) = a.get(startIndex); // error here
a.get(startIndex) = min; // error here
}
}
}```
class-SortDouble
{
公共静态void main(字符串[]args)
{
int n=10;
ArrayList a=新的ArrayList();
随机r=新随机();
对于(int i=0;i
要更新Arraylist中特定索引处的值,我们使用方法。
将导致错误的两行更改为:
a.set(indexOfMin, a.get(startIndex)); // a[indexOfMin] = a[startIndex];
a.set(startIndex, min); // error here // a[startIndex] = min;
谢谢,这就解决了!我试着使用set方法,但我用错了。而不是使用a.set(indexOfMin,a.get(startIndex))代码>我刚刚有了a.set(indexOfMin,startIndex)代码>,我不知道还需要get()方法,谢谢您的解决方案!啊,我是新来的。我这么做了,虽然它不会显示我的投票,因为我是新的!谢谢你让我知道这件事!