Reputation: 231
What is the best way of building an ArrayList<>
from a List<>
?
An Example would be great
and another question, should i keep working with a List<>
instead of converting all my Lists
to ArrayLists
Edit
Just to be sure of my code : can this work :
public List<Rendezvous> getAllNewlyDoneRdvs() {
if (!isThereNewlyDoneRdvs())return null;
List<Rendezvous> rdvs = rdvDao.findAllByState(Constants.rdvStateUndone);
ArrayList<Rendezvous> rendezvousList = new ArrayList<>();
for (Rendezvous rdv :rdvs ){
if (rdv.getDateRdv().before(Constants.getCurrentDatetime())) rendezvousList.add(rdv) ;
}
rdvs = rendezvousList;
return rdvs;
}
Upvotes: 0
Views: 137
Reputation: 174
It sheems you are comparing the dates first and then preparing the new list.
This is absolutely fine. But in this case you should have another method in DAO itself which returns the List of Rendezvous having DateRdv before current date.
Upvotes: 0
Reputation: 59093
You can get caught out if you have a method taking a List
parameter because some implementations of List
(even in the standard library) are immutable or are of a fixed size.
In which case, if you need a mutable list, it's completely reasonable to create an ArrayList
with the same contents as your existing uncertain-implementation List
ArrayList<T> newArrayList = new ArrayList<T>(oldList);
Upvotes: 0
Reputation: 744
You should know that List is an Interfaces and ArrayList is a concrete class, so you should always use
List<Type> myList = new ArrayList<Type>();
Upvotes: 1
Reputation: 309
It will be good practice using List while declaring.
List<> list = new ArrayList<>();
Upvotes: 1
Reputation: 13727
If you want to be sure that you have an ArrayList to work with, you can just do new ArrayList(existingList)
.
The best reason for doing this might be that you want to add, update, or remove items from the list without affecting the original list.
Upvotes: 3
Reputation: 240870
assumming both of the type are same
List<>
could be already an ArrayList<>
in that case just change reference
if not iterate and add
Upvotes: 4