Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (5.3k points)

(1) List<?> myList = new ArrayList<?>(); (2) ArrayList<?> myList = new ArrayList<?>();

I know that with (1) the implementations of the List interface can be swapped. It seems that (1) is typically used in applications regardless of need (I always use this myself).

Does anyone use (2)?

Also, how often does the situation actually require using (1) over (2) [i.e., where (2) wouldn't suffice..aside coding to interfaces and best practices, etc.]?

Please explain with an example

1 Answer

0 votes
by (119k points)

The list is preferred over ArrayList because List can be translated into a LinkedList without affecting the remaining codebase.

For example, you have decided LinkedList is better to use for your application, but later you have decided ArrayList might be a better considering performance reason.

Use:

List list = new ArrayList(100); //  also better to set the initial capacity of a collection 

Instead of:

ArrayList list = new ArrayList();

If you want to learn Java, then you can take up this Java Training by Intellipaat.

Related questions

0 votes
2 answers
0 votes
1 answer
asked Feb 24, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked Apr 4, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Mar 6, 2021 in Java by dante07 (13.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...