How list methods works in java [closed]

旧街凉风 提交于 2019-12-31 07:42:16

问题


List is an interface in java. And it has some methods. Generally an interface is a specification of method prototypes. i.e. interface consist of methods signature only no implementation will be there for that methods in interface.

I have a doubt that how the methods of List interface work if they don't have any implementation inside the interface.

Suppose I have a class Book which has name property, setter,getter methods. and I have another class getBooks like this.

public class GetBooks{
    List<Book> list;
    public List<Book> getBooks(){
    return list;
    }
    //setter method..
}

I am sending books into the set method at runtime through some other class.

I have another class UseBooks like this.

public class UseBooks{
    .....
    ....
    List<Book> list = new GetBooks().getBooks();
    list.add(new Book("aaa"));
}

My question is how add method is adding books even it is in interface List because my getBooks() returning List interface not Arraylist or some other implementation class.


回答1:


Java provides 3 concrete classes which implement the list interface
Vector
ArrayList
LinkedList



回答2:


The only objects of type List you will be using will be types which actually implement List, like ArrayList, LinkedList etc. They will provide the implementations.

You cannot instantiate a class which has unimplemented abstract methods from super classes or interfaces.




回答3:


"I have a doubt that how the methods of List interface work if they dont have any implementation inside the interface" -(!!!!!!) It will use the implementation of any class instance which is implemented this interface. So depends on the implementation in different class instance.

Are you expecting any kind of detailed example for this?




回答4:


java.util.ArrayList, java.util.LinkedList, java.util.Vector are concrete implementation class of List interface. This classes contains all method implementation. You can use like -

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


来源:https://stackoverflow.com/questions/14252068/how-list-methods-works-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!