Trouble sorting objects in an array by property
in
Programming Questions
•
2 years ago
I've gathered a lot of tweets and am attempting to sort them by username, date, and content. I've created a class that breaks them down into pieces and stores each of those items as a property of the object. What I'm having trouble with is sorting the objects based on those properties. I've tried following suggestions in this forum:
http://processing.org/discourse/yabb2/YaBB.pl?num=1231046066/9 but am getting a Null Pointer Exception on the line
String user2 = ((Tweet) o2).getUsr();. My code is below. Thanks for any suggestions!
Tweet tweet;
int l;
String[] lines;
int index = 0;
Tweet[] tweets = new Tweet[100];
void setup(){
lines = loadStrings("tweets0.txt");
}
void draw(){
for(int index = 0; index < 100; index++){
String[] pieces = split(lines[index], '~');
if(pieces.length == 3){
tweets[index] = new Tweet(index, 0, 0, 0, pieces[0], pieces[1], pieces[2]);
//println(tweets[index].username);
}
Arrays.sort(tweets, new UserComparator());
for(int i = 0; i < 100; i++){
println(tweets[i].username);
}
}
noLoop();
}
class Tweet {
int id;
int xcord;
int ycord;
int zcord;
String username;
String date;
String content;
Tweet(int tempid, int tempxcord, int tempycord, int tempzcord, String tempuser, String tempdate, String tempcontent) {
id = tempid;
xcord = tempxcord;
ycord = tempycord;
zcord = tempzcord;
username = tempuser;
date = tempdate;
content = tempcontent;
}
String getUsr(){
return username;
}
String getDate() {
return date;
}
String getCont(){
return content;
}
}
class UserComparator implements Comparator {
int compare(Object o1, Object o2) {
String user1 = ((Tweet) o1).getUsr();
String user2 = ((Tweet) o2).getUsr();
return user1.compareTo(user2);
}
}
1