ok; i am making a project for school and its a game similar to falling sand. but in order for the gravity to work i have to have the sand sorted by its position from down to up (the y variable of sand) this method should sort it; although i cannot get .clone() to work and i can’t hard copy any other way i know. so i don’t know how to replace all the comments in this code with something that will do what they say.
to explain how i want this to work; i want it to, one by one, remove elements from world while i place them sorted in sorted.
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
}
the error i am getting with clone is:
awesomesand.java:48: clone() has protected access in java.lang.Object
sand a=world.get(0).clone();
and, yes world is of type sand.
EDIT
now i am getting an error on cloning.
awesomesand.java:48: incompatible types
found : java.lang.Object
required: awesomesand.sand
sand a=world.get(0).clone();
^
You are getting the clone exception because it has protected access in
Object. However, sorting an ArrayList does not needclone()if you invoke the standard sorting mechanisms of Collections.As for why you’re getting the clone error, a class must override
clone()with public access. This is to assure that you handle the specifics of your class:However, easier, more efficient, and more likely correct, is to just sort the collection of sand objects directly. Here I’ve defined a possible version of Sand, and show the use of Collections.sort: