【发布时间】:2017-12-06 06:18:30
【问题描述】:
我是编程新手,在将具有日期和时间属性的对象的 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;
}
如果我在没有排序方法的情况下运行完整程序,我会得到以下输出:
如果我使用“排序”算法,我会得到:
如果有人可以向我解释我做错了什么或指出我正确的方向,我将不胜感激。谢谢!
更新: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;
}
有人建议我使用比较,如果没有其他解决方案提供给我,我会使用比较,但我认为技术上不允许我这样做(这是为了分配)。
【问题讨论】:
-
Sort Java Collection的可能重复
-
请take the tour 了解该网站的运作方式以及此处的主题问题,并edit 相应地提出您的问题。另见:How to Debug Small Programs
-
使用 Collections.sort(yourList,new TweetComparator())。阅读本文档,了解如何实现比较器javatpoint.com/Comparator-interface-in-collection-framework
-
也许您还应该显示
isBefore方法,发布代码的逻辑似乎是正确的(有点难以理解)。实际上Minimal, Complete, and Verifiable example 会有所帮助(远远超过结果的屏幕截图)