Java ArrayList 与自定义 AddAll 方法

标签 java android arraylist

我有一个名为News的自定义类,每个新闻都有一个唯一的id:

public class News{ 
    public long id;
    public String title;
    //...
}

现在我想为我的数据集使用自定义的ArrayList

这是我的自定义ArrayList:

public class NewsArrayList<E> extends ArrayList<News> {
    @Override
    public boolean addAll(Collection<? extends News> c) {
        ArrayList<News> b = new ArrayList<>();
        boolean notExists;
        for (News n : c) {
            notExists = true;
            for (News ex : this) {
                if (n.id == ex.id) {
                    notExists = false;
                    break;
                }
            }
            if (notExists)
                b.add(n);
        }
        return super.addAll(b);
    }
}

如果我像这样使用这些类:

ArrayList<News> myNews = mDatabase.getNewsByOffset(5,10); // will return first 5 News from database
NewsArrayList<News> mDataset = new NewsArrayList<>();
mDataset.addAll(myNews);
myNews = mDatabase.getNewsByOffset(4,10); // will return first 4 News from database
mDataset.addAll(myNews);

那么此代码是否安全并经过优化,不会在 mDataset 中出现重复的 News 项目?

还有一个简单的问题,这个 break; 会破坏所有 for 循环 还是仅破坏内部循环?

....
for (News n : c) {
    notExists = true;
    for (News ex : this) {
        if (n.id == ex.id) {
            notExists = false;
            break;
        }
    }
    if (notExists)
        b.add(n);
}
....

最佳答案

如果您想要一个没有重复的集合,请考虑使用Set,如果您想保持顺序,请使用 LinkedHashSet ,您只需要在 News 类中重写方法 equalshashCode 即可。

例如这样:

@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || this.getClass() != o.getClass()) return false;

    final News news = (News) o;

    return this.id == news.id;

}

@Override
public int hashCode() {
    return (int) (this.id ^ this.id >>> 32);
}

您的代码将是:

ArrayList<News> myNews = mDatabase.getNewsByOffset(5,10); // will return first 5 News from database
Set<News> mDataset = new LinkedHashSet<>(myNews);
myNews = mDatabase.getNewsByOffset(4,10); // will return first 4 News from database
mDataset.addAll(myNews);

但是,如果您确实需要使用不重复的List,您仍然可以继续下一步:

List<News> mDataset = new ArrayList<>(new LinkedHashSet<>(myNews));

and just another quick question, this break;, breaking all for-loops or the inner one only?

它只会打破内部循环来打破所有使用标签作为 next 的 for 循环:

main: for (News n : c) {
    ...
    for (News ex : this) {
        if (n.id == ex.id) {
            ...
            // Break the loop with the label main
            break main;
        }
    }
    ...
}

关于Java ArrayList 与自定义 AddAll 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114508/

相关文章:

java - 在可变数量的 double 中找到平均值

java - Spring JMS 并发和 JMSXGroupID

android - 在某些 Fragments 中隐藏 Tablayout

java - Jackson:忽略 Json 配置值

android - Intents 目录及其使用方法

android - 编程按钮/图像的最佳方式

java - 将圆形对象添加到数组列表并显示在屏幕上

jpa - 如何在JPA中保留Entity类型的数组列表

java - Spring事务没有正确回滚

java - GWT/Java 中等待多个异步事件完成的干净方式