Kian
Kian

Reputation: 19

How can I initialize a List<Record> Object in java

the return type is List and I declare list for returning and how can I actually declare it after new?

public List<Record> findClosestRecords(int n) throws IndexException {
    if (!sorted || n > records.size()) {

    }
    List<Record> list = new ;
    for (int i = 0; i < n; i++) {
        Record r = this.records.get(i);
        list.add(i, r);
    }
    return list;
}

Upvotes: 1

Views: 8883

Answers (3)

Jyr
Jyr

Reputation: 711

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

or use diamond syntax;

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

This is implying you implemented the List interface by means of an ArrayList.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

You can try like this:

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

Note that List is an interface and you cannot initialize an interface. So you need to create an object which implements the List interface.

Upvotes: 5

Upio
Upio

Reputation: 1374

You have to instantiate a concrete implementation of the List interface. The most common one is ArrayList but you can find others in the documentation https://docs.oracle.com/javase/7/docs/api/java/util/List.html

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

Upvotes: 2

Related Questions