Santiago Gil Santiago Gil - 4 years ago 118
Java Question

Sort implementing Comparable not working on Android

I implemented Comparable on my clas News so that I could arrange an Array of News by publishDate

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class News implements Comparable<News>{

private String title;
private String description;
private String link;
private String guid;
private String pubDate;
private Date date;
private String author;
private String image;
private String category;
private String feedIconLink;

public int compareTo(News anotherNews) {

long compareDateInMilisecconds = ((News) anotherNews).getDateInMilliseconds();

long result = compareDateInMilisecconds - this.getDateInMilliseconds();

int finalResult = (int) result;

return finalResult;

The code compiles and it runs and it thows no error, but it does not actually change the order of the objects on the Array.

protected void onPostExecute(List<News> input) {

for (News aNews : input){
Log.v("Before", aNews.getFeedIconLink());


for (News aNews : input){
Log.v("After", aNews.getFeedIconLink());



I Log.v before and after sorting and there is no change, even though on debug it runs through the whole CompareTo method for the whole Array.

Is there something I'm doing wrong?

Answer Source

You are:

  • Converting the List<News> into a News[]

  • Sorting the News[]

  • Throwing away the News[]

Instead, sort the List<News>, using Collections.sort(), instead of Arrays.sort().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download