简体   繁体   English

在Java中声明和使用List

[英]Declare and use List in java

I just touch java, I found if I need to create a new list 我只是触摸java,发现是否需要创建新列表

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

But in my homework, the code is like following. 但是在我的作业中,代码如下。 In the function Postering, the parameter is List<Integer> positions . 在函数Postering中,参数为List<Integer> positions Can we put 'ArrayList' there? 我们可以把“ ArrayList”放在那里吗? Or usually we usually put List there? 还是通常我们通常将List放在那里?

Could someone explain this in a detailed way? 有人可以详细解释吗?

static class Posting {
int docID;
List<Integer> positions;
public Posting(int docID, List<Integer> positions) {
  this.docID = docID;
  this.positions = positions;
}

} }

List<Integer> is an interface ; List<Integer>是一个接口 ArrayList<Integer> is a class implementing that interface. ArrayList<Integer>是实现该接口的类。 You should use List<Integer> , because it lets the caller change the implementation - for example, LinkedList<Integer> . 您应该使用List<Integer> ,因为它允许调用者更改实现-例如, LinkedList<Integer>

This technique for improving flexibility is known as programming to an interface. 这种提高灵活性的技术被称为接口编程。 You can read more about its advantages in answers to this question . 您可以在此问题的答案中详细了解其优点。

您可以使用ArrayList但最好使用其接口List

You can use both ArrayList and List . 您可以同时使用ArrayListList

ArrayList is an implementation of List (such as LinkedList , for example). ArrayListList的实现(例如LinkedList )。

List is an interface, which only describes the methods called by implementations. List是一个接口,仅描述实现调用的方法。

By using the interface, the method which call the constructor of your class will be able to use ArrayList or LinkedList (or an other one ). 通过使用该接口,调用您的类的构造函数的方法将可以使用ArrayListLinkedList (或另一个 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM