编写一个方法,用于将列表元素存储到变量中,以便使用数组中的下一个元素进行切换 目前有两个存储变量(可能或可能不意味着有额外的存储)。
目标是使用正确的迭代器(除非有更好的方法)将存储的元素切换为尽可能少的行中的下一个。
public void sort(List<Point> lst) {
for (int st = 0; st < lst.size(); st++) { //defines first element-to-compare.
for (int wt = 1; wt< lst.size(); wt++) { //defines second element-to-compare.
double one = lst.get(st).distanceToOrigin(); //stores variable describing distance-to-origin for point one;
//if lst.get(st)>lst.get(wt), am switching element places in list.
//if lst.get(st) > lst.get(wt), switch the pair of consecutive elements.
double two = lst.get(wt).distanceToOrigin(); //stores variable describing distance-to-origin for point two;
//represents element to switch if lst.get(wt) < lst.get(st)
Point tmp1;
Point tmp2;
if (one > two){
tmp1 = lst.get(st);
lst.remove(lst.get(st));
tmp2 = lst.nextPoint();
}
}
}
}
现在我正在使用hasNext()
方法来检查lst.get(st)之后是否还有其他元素:
if (one > two) {
tmp1 = lst.get(st);
lst.remove(lst.get(st));
while (lst.distanceToOrigin.hasNext()) { //this line does not work in editor.
//Attempting to refine.
//TODO switch elements described by double one and double two.
}
}
非常感谢Insight。
答案 0 :(得分:1)
您可以使用List
的方法更改元素顺序:
if(one > two) {
Point tmp1 = list.get(st);
Point tmp2 = list.get(wt);
lst.set(st, tmp2);
lst.set(wt, tmp1);
}
//....
另一种方法:如果每个Point-Object&#34;都知道&#34;原点,它也可以是使用Comparable-Interface
:
public class Point implements Comparable {
Point origin;
//other variables...
//constructor and methods...
@Override
public int compareTo(Point other) {
Double.compare(this.distanceToOrigin(), other.distanceToOrigin());
}
}
您的sort()-method
:
public void sort(List<Point> lst) {
Collections.sort(lst);
}