Java make custom object comparable? -


i have object below.

public class coords {      public int x;     public int z;      public coords(int x, int z) {         this.x = x;         this.z = z;     }  } 

how can implement compareable? im not sure compareto method should doing.

@override public int compareto(object o) {     // todo auto-generated method stub     return 0; } 

you compare x , compare z (alternatively, z , x). also, suggest override tostring. like,

public class coords implements comparable<coords> {     public int x;     public int z;      public coords(int x, int z) {         this.x = x;         this.z = z;     }      @override     public int compareto(coords o) {         if (this.x == o.x) {             if (this.z == o.z) {                 return 0;             }             return this.z < o.z ? -1 : 1;                        }         return this.x < o.x ? -1 : 1;     }      @override     public string tostring() {         return string.format("{%d, %d}", x, z);     } } 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -