开发者

What does it means by returning an interface Object in Java? [closed]

Closed. This question needs details or clarity. It i开发者_运维技巧s not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 8 years ago.

Improve this question

First, check out this document first:

http://htmlcleaner.sourceforge.net/doc/org/htmlcleaner/TagNode.html

It have a function called:

getAllElementsList(boolean isRecursive).

and it will return me something called:

List

Ok, when I go to this the document of "List", I check this: http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html

Which is an interface:

public interface List<E> extends Collection<E>

My question is....What does it expand me to do? He want me to have an object which implemented the List interface can get be used as a return type?

Also, what is the <E> means? Thank you.


Interfaces are always preferred as return types, because the code can later switch to another implementation (for example, optimizing performance), but all client code will continue to work.

<E> is a generic definition, when using a List you can specify what type of objects you want it to hold. For example List<String>. This ensures compile-time safety when working with the list elements.


Yes, you need to return anything that implements List<E>, e.g. ArrayList<E> or LinkedList<E>.

The <E> is a generic type, i.e. you can replace it with a concrete class or interface, e.g. List<Integer> to define the list to contain Integer objects only.

Note that List and List<E> are different, with generic type checking being disabled for the former. If the method has the return type List it's most probably old code or for compatibility reasons with Java prior to 1.5. Nowadays you'd most probably use List<?> as the return type if that wouldn't matter.


<E> is the generic collection element name.

Returning a "List" is a form of "data hiding" - you obscure the actual implementation so that you can change it and they don't hardcode in dependencies on it. You're really going to be returning something that implements list, but by saying you return List, you're returning an Interface rather than a Type (which is a design principle).


That function returns an Object whose class implements List! And, E is a place-holder.


Yes, it returns an object that implements the interface List. ArrayList is an example.

The E is the type of the object that the list will contain.

Maybe the code below can help you more.

List<String> lString = new ArrayList<String>();
lString.add("test1");
lString.add("test2");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜