Omid Omid - 1 month ago 11
Java Question

Java ArrayList with customized AddAll method

I have a custom class called

News
every news have a unique
id
for itself:

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


now I want to use an customized
ArrayList
for my
dataset


And this is my custom
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);
}
}


if I'm using those classes like this:

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);


Then will this code safe and optimized to not having dupplicate
News
items in
mDataset
?

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

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

Answer

If you want a collection with no duplicate consider using a Set instead, if you want to keep the order use a LinkedHashSet, you will simply need to override the methods equals and hashCode in your class News.

For example like this:

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

    final MainTest.News news = (MainTest.News) o;

    return this.id == news.id;

}

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

Your code would then be:

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);

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

It breaks the inner loop only to break all for loops use a label as next:

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