Sorting ArrayList objects using float
In your StockPrice class, you can implement Comparable. It will look like this:
public class StockPrice implements Comparable<StockPrice> {
// All your code here
@Override
public int compareTo(StockPrice another) {
// price fields should be Float instead of float
return this.price.compareTo(another.price);
}
}
Then you can use Collections.sort()
source to share
According to the jdk 1.7 requirement, the results should be the same if you change the position of params. So the subtraction will be wrong, I think this is the simplest way to sort floating point arrays:
Collections.sort(Arrays, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return Float.compare(o1.getFloatValue(), o2.getFloatValue());
}
});
source to share
I am assuming you have a class to store your prices. The easiest way is to implement Comparable in this class and return there like Float.compare(this.price, other.price)
.
source to share
You need to implement the Comparable interface and define a compareTo () method for your class. Once you're done, you can have an arrayist and sort it. See the link for an example. A few more links with importers another example and the difference between comparable and useful comparator information
source to share