I have made a class as follows:
class strVal{
double val;
String str;
}
Now I made an array of this class now I want to sort that array by strVal.val. I want to know if there is any standard defined method in Java?
Implement java.lang.Comparable interface, and use java.util.Arrays.sort(...) to sort an array of StrVal:
public class StrVal implements Comparable<StrVal> {
private double val;
private String str;
public StrVal(double val, String str) {
this.val = val;
this.str = str;
}
@Override
public int compareTo(StrVal o) {
return (int)(this.val - o.val);
}
public double getVal() {
return val;
}
public String getStr() {
return str;
}
}
To sort the array :
StrVal[] array;
...
Arrays.sort(array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With