所以,我试着按照物体区域的顺序打印出我的排列表。但是,我似乎不知道如何在索引处将对象的值传递给对方。(我必须反复做)。这是我的代码
private static void recursionSort(ArrayList<GeometricObject> data)
{
if(data.size() <= 1) return; // Base case: just 1 elt
ArrayList<GeometricObject> a = new ArrayList<GeometricObject>(data.size() / 2);
ArrayList<GeometricObject> b = new ArrayList<GeometricObject>(data.size() - a.size()); // Split array into two
// halves, a and b
for(int i = 0; i < data.size(); i++)
{
if(i < a.size())
a.indexOf(i) = data.get(i);
else
b.get(i - a.size()) = data.get(i);
}
recursionSort(a); // Recursively sort first
recursionSort(b); // and second half.
int ai = 0; // Merge halves: ai, bi
int bi = 0; // track position in
while(ai + bi < data.size()) { // in each half.
if(bi >= b.size() || (ai < a.size() && a.get(ai).getArea() < b.get(bi).getArea())) {
data.get(ai + bi) = a.get(ai); // (copy element of first array over)
ai++;
} else {
data.get(ai + bi) = b.get(bi); // (copy element of second array over)
bi++;
}
}
}我的问题是台词
a.indexOf(i) = data.get(i);
b.get(i - a.size()) = data.get(i);
data.get(ai + bi) = a.get(ai);
data.get(ai + bi) = b.get(bi); 例如,我不知道如何使a的索引0等于我的列表的(数据)索引0。如果这些是数组,我会知道该做什么,所以让我用它作为一个例子,向你们展示我试图通过数组来完成的任务。
a[i] = data[i]; // First line in block above
data[ai + bi] = b[bi]; // Last line in block above任何帮助都将不胜感激。我已经浏览了我的书中的ArrayList类方法列表中的所有方法,但是没有一个方法具有我想要的效果。谢谢!
发布于 2015-10-14 03:52:31
List接口定义了set(int index, E element) (在本例中为E= GeometricObject )。因此,您遇到问题的四行应该重写如下:
a.set(i, data.get(i));
b.set(i - a.size(), data.get(i));
data.set(ai + bi, a.get(ai));
data.set(ai + bi, b.get(bi));希望这能帮上忙。
杰夫
发布于 2015-10-14 04:12:42
不必实现排序方法就可以使用自定义对象对Arraylist进行排序。您可以使用Collections.sort(arraylist)进行同样的操作。
为了使用相同的功能,您需要根据需要使用()、使用Comparator或Comparable接口。
如果使用Comparable接口,代码如下所示:
public class GeometricObject implements Comparable<GeometricObject>
{
// member variables
// other methods
@Override
public int compareTo(GeometricObject comparesToObject)
{
// wil sort in ascending order.
return this.getArea()-comparesToObject.getArea();
// Use the commented line for descending order
// return comparesToObject.getArea() - this.getArea();
// Use return Float.compare(area1, area2) if area is of type float.
}
}
// This will now sort your data Arraylist.
Collections.sort(data);https://stackoverflow.com/questions/33116198
复制相似问题