Santiago Gil Santiago Gil - 4 months ago 9
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;



@Override
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.

@Override
protected void onPostExecute(List<News> input) {

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

Arrays.sort(input.toArray());

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

}

this.listener.finish(input);
}


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

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().

Comments