Aissasa
Aissasa

Reputation: 231

Build an ArrayList<> from a List<>

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

Answers (7)

Hansraj
Hansraj

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

khelwood
khelwood

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

kakashy
kakashy

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

paulk23
paulk23

Reputation: 465

You could use Collections.list() as illustrated here

Upvotes: 0

Niamath
Niamath

Reputation: 309

It will be good practice using List while declaring.

List<> list = new ArrayList<>();

Upvotes: 1

Jon Onstott
Jon Onstott

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

Jigar Joshi
Jigar Joshi

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

Related Questions