Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in these two declarations?

Tags:

java

List<String> someName = new ArrayList<String>();

ArrayList<String> someName = new ArrayList<String>();
  1. Does it impact anything on performance?
  2. The first one is a List of Objects and the latter one is ArrayList of Objects. Correct me if i am wrong. I got confused because ArrayList implements List Interface.
  3. Why do people declare like this? Does it help in any situtions.
  4. When i am receiving some email address from DB, what is the best way to collect it? List of eMail address Objects????
  5. Finally one unrelated question.... can an interface have two method names with same name and signature and same name with different signature.
like image 618
John Cooper Avatar asked Mar 20 '26 10:03

John Cooper


1 Answers

The difference between the declarations is more one of style. It is preferable to declare variables using the abstract, rather than the concrete implementation, because you can change the implementation choice later without changing the variable type. For example, you might change the List to use a LinkedList instead.

If you always use the abstract type (interface or abstract class) wherever you can, especially in method signatures, the client code is free to use whatever implementation they prefer. This makes the code more flexible and easier to maintain.

This is true even of variable declarations. Consider this:

public abstract class MyListUsingClass {

    private List<String> list;

    protected MyListUsingClass(List<String> list) {
        this.list = list;
    }

    ...
}

If the variable list was declared as ArrayList, then only ArrayLists would be accepted in the constructor. This would be a poor choice: Always try to let the client code chose the implementations they want to use.

Regarding you last question: Interfaces have the same restrictions for methods as classes do, so yes you can overload methods.

like image 103
Bohemian Avatar answered Mar 26 '26 14:03

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!