gpt4 book ai didi

java - 按自制类的变量之一对自制类的数组列表进行排序,而clone()将不起作用

转载 作者:行者123 更新时间:2023-12-01 17:40:44 25 4
gpt4 key购买 nike

好的;我正在为学校制作一个项目,它是一个类似于落沙的游戏。但为了让重力起作用,我必须让沙子按其位置从下到上排序(沙子的 y 变量),这个方法应该对它进行排序;虽然我无法让 .clone() 工作,并且我无法以我知道的任何其他方式进行硬复制。所以我不知道如何用能够按照他们所说的方式替换此代码中的所有注释。

解释我希望它如何工作;我希望它能够一一从世界中删除元素,同时将它们排序。

   public void sort(){
//method to sort elements by y value
ArrayList<sand> sorted=new ArrayList<sand>();
if(world.size()!=0){
//code to take 0 from world and place it into sorted at 0
while(world.size()>0){
boolean check=true;
for(int i=0;i<sorted.size();i++){
if(world.get(0).y<sorted.get(i).y){
//code to take 0 from world and place it into sorted at i
check=false;
}
}
if(check){
//code to take 0 from world and place it at the end
}
}
}
//code to make sorted the contents of world
}

我在克隆时遇到的错误是:

awesomesand.java:48: clone() has protected access in java.lang.Object
sand a=world.get(0).clone();

而且,是的,世界是沙子类型的。

<小时/>

编辑

现在我在克隆时遇到错误。

awesomesand.java:48: incompatible types
found : java.lang.Object
required: awesomesand.sand
sand a=world.get(0).clone();
^

最佳答案

您收到克隆异常,因为它在 Object 中具有 protected 访问权限。但是,如果调用 Collections 的标准排序机制,则对 ArrayList 进行排序不需要 clone() .

至于为什么会出现克隆错误,类必须使用公共(public)访问权限重写 clone() 。这是为了确保您能够处理类(class)的具体情况:

public class Sand implements Cloneable {
public Object clone() throws CloneNotSupportedException {
Sand copy = (Sand) super.clone();
// Sand specific copying done here
return copy;
}
}

然而,更简单、更高效、更可能正确的方法是直接对沙子对象的集合进行排序。这里我定义了 Sand 的一个可能版本,并展示了 Collections.sort 的使用:

public class Sand {
public int x;
public int y;
}

public class SandComparator implements Comparator<Sand> {
public int compare(Sand s1, Sand s2) {
// reverse these to sort in the opposite order
return s1.y - s2.y;
}
public boolean equals(Object o) {
return o instanceof SandComparator;
}
}

public class App {
ArrayList<Sand> world;
...
public void sort() {
Collections.sort(world, new SandComparator());
}
}

关于java - 按自制类的变量之一对自制类的数组列表进行排序,而clone()将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/962701/

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