我是编程新手,我在按时间顺序排序具有日期和时间属性的对象的ArrayList时遇到了一些困难。我在我的isBefore方法上运行了很多测试,它确定哪个Tweet对象在另一个之前,并确定它没问题。这意味着我的问题可能在于我用来对ArrayList进行排序的算法。
private void sortTwitter(){
ArrayList<Tweet> temp = new ArrayList<Tweet>();
while(getSizeTwitter()>1){
int indexOfEarliest = 0;
for(int i = 0; i<getSizeTwitter(); i++){ //finds the index of the earliest tweet in the tweets ArrayList
//The Tweet object at [0] is tweets.get(0).
//The Tweet object we want to compare it to initially is tweets.get(1). Specifically, we want tweets.get(1).getDate() and .getTime()
Tweet tweet1 = this.tweets.get(indexOfEarliest);
Tweet tweet2 = this.tweets.get(i);
boolean tweet1Earlier = tweet1.isBefore(tweet2.getDate(), tweet2.getTime());
if(tweet1Earlier == false){ //Supposed to update the value of indexOfEarliest to the index of tweet2 is tweet2 is earlier.
indexOfEarliest = i;
}
}
temp.add(this.tweets.get(indexOfEarliest));
this.tweets.remove(indexOfEarliest);
}
//Now tweets is an array of 1 element, the largest.
temp.add(this.tweets.get(0));
this.tweets.clear();
this.tweets = temp;
}
如果我在没有排序方法的情况下运行完整程序,我会将其作为输出:
如果我使用&#34;排序&#34;算法,我明白了:
如果有人能够向我解释我做错了什么或者指出了我正确的方向,我将非常感激。谢谢!
更新:isBefore
public boolean isBefore(String sTestDate, String sTestTime){
String[] splitTweetDate = this.date.split("-"); //Reconfigures the format of Tweet instance date and time
String[] splitTweetTime = this.time.split(":");
int[] tweetDate = stringToInt(splitTweetDate);
int[] tweetTime = stringToInt(splitTweetTime);
String[] splitTestDate = sTestDate.split("-"); //Reconfigures the format of query parameters
String[] splitTestTime = sTestTime.split(":");
int[] testDate = stringToInt(splitTestDate);
int[] testTime = stringToInt(splitTestTime);
for(int i = 0; i<3; i++){ //Tests the date year first, then month, then day. Returns true if tweetDate is earlier than testDate.
if(tweetDate[i]<testDate[i]){
return true;
}
}
for(int i = 0; i<3; i++){ //If on the same day, tests hour first, then minutes, then seconds. Returns true if tweetTime is earlier than testDate.
if(tweetTime[i]<testTime[i]){
return true;
}
}
return false; //If method returns nothing, message was posted at the same time or later.
}
//HELPER 2
private int[] stringToInt(String[] arrString){ //converts an array of strings into an array of integers.
int[] arrInt = new int[arrString.length];
for(int i = 0; i<arrInt.length; i++){ //parseing the elements of the string array to integers.
arrInt[i] = Integer.parseInt(arrString[i]);
}
return arrInt;
}
有人建议我使用比较,如果没有其他解决方案提交给我,我会的,但我不认为我在技术上允许(这是作业)。
答案 0 :(得分:0)
使用java.util.Comparator
创建单独的排序机制,并通过比较java.util.Date
并简单地调用Collection.sort(<customList>, Comparator<>);
来提供标准,无需手动循环。请查看示例如何使用java.util.Date
实现Comparator,您将会有所了解。它也会减少你的代码行数。