2

I just touch java, I found if I need to create a new list

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 . Can we put 'ArrayList' there? Or usually we usually put List there?

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;
}

}

user3495562
  • 335
  • 1
  • 4
  • 16

3 Answers3

2

List<Integer> is an interface; ArrayList<Integer> is a class implementing that interface. You should use List<Integer>, because it lets the caller change the implementation - for example, 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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You can use ArrayList but it's better to use its interface List.

Alex
  • 11,451
  • 6
  • 37
  • 52
1

You can use both ArrayList and List.

ArrayList is an implementation of List (such as LinkedList, for example).

List is an interface, which only describes the methods called by implementations.

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).

Happy
  • 1,815
  • 2
  • 18
  • 33