android使用binarySearch获取要添加到List

时间:2016-04-25 15:43:00

标签: android arraylist z-index binary-search

嗨我有和android app构建对象列表(topStories)。将新项TopStory添加到列表(topstories)时(列表初始为空ArrayList)。我想确定新项目应添加的index,以便List topstories按特定变量(TopStory.time)的顺序保留。如何使用binarySearch来确定索引。 Anyhelp非常适合。感谢

这是我的模型类

public class TopStory {
    private int id;
    private String title;
    private String author;
    private int score;
    private JSONArray kids;
    private long time;
    private String url;

    public TopStory() {
    }

    public TopStory(int id, String title, String author, int point, long time,String url) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.score = point;
        this.time = time;
        this.url = url;
    }

我使用过这些代码但有错误

int index = Collections.binarySearch(topStories,topStory, new Comparator<TopStory>() {
                            @Override
                            public int compare(TopStory lhs, TopStory rhs) {
                                return (int) (rhs.getTime()-lhs.getTime());
                            }

                            @Override
                            public boolean equals(Object object) {
                                return false;
                            }
                        });
topStories.add(index, topStory);

错误是

java.lang.IndexOutOfBoundsException: Invalid index -1, size is 0
                                                                       at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                       at java.util.ArrayList.add(ArrayList.java:147)
                                                                       at com.vic.hackernew.ItemListActivity$5.onResponse(ItemListActivity.java:199)
                                                                       at com.vic.hackernew.ItemListActivity$5.onResponse(ItemListActivity.java:182)

0 个答案:

没有答案