gpt4 book ai didi

android - 按时间升序存入ArrayList

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:13 25 4
gpt4 key购买 nike

我目前的数据结构如下:

public class MyDataTemplate {

long occurenceTime;
int val1;
int val2;

public MyDataTemplate(Long nanoTime, int val1, int val2) {
this.occurenceTime = nanoTime;
this.val1 = val1;
this.val2 = val2;
}

}

List<MyDataTemplate> myData = new ArrayList <MyDataTemplate>();

上面的occurenceTime(long)表示我在Android中使用System.nanoTime()获取的系统时间

如果数据按时间顺序到达,我可以很好地使用上述数据结构在数据到达时存储数据:

newOccurence = new MyDataTemplate(System.nanoTime(), 42, 55)        
myData.add(newOccurence);

但是,由于数据不是按顺序到达的,我可能会比旧事件更早地得到新事件。

我的任务是确保 myData 包含按时间升序排列的数据,无论数据何时到达。

我怎样才能确保这一点?

最佳答案

Frog 燕麦...

我做了一个尝试,似乎粗略地说明了一个潜在的“解决方案”:

public class MainActivity extends AppCompatActivity {

public class MyDataTemplate {


long occurenceTime;
int val1;
int val2;

public MyDataTemplate(Long nanoTime, int val1, int val2) {
this.occurenceTime = nanoTime;
this.val1 = val1;
this.val2 = val2;
}

}

class SortByNanoTime implements Comparator<MyDataTemplate> {

public int compare(MyDataTemplate a, MyDataTemplate b) {
if (a.occurenceTime < b.occurenceTime)
return -1;
else if (a.occurenceTime > b.occurenceTime)
return +1;
else
return 0;
}
}

List<MyDataTemplate> myData = new ArrayList<MyDataTemplate>();


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

myData.add(new MyDataTemplate((long) 30000.2341, 2, 3));
myData.add(new MyDataTemplate((long) 234234.234, 3, 4));
myData.add(new MyDataTemplate((long) 11234234.234, 3, 4));
myData.add(new MyDataTemplate((long) 4.234, 3, 4));

Collections.sort(myData, new SortByNanoTime());

for (MyDataTemplate tempVar : myData) {

Log.i("XXX", "" + tempVar.occurenceTime);

}


}
}

关于android - 按时间升序存入ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49766227/

25 4 0