通用接口中的ArrayList返回类型-预期<identifier>

时间:2018-12-08 11:06:35

标签: java arraylist

我有以下界面:

public interface IRepository<T> {   
    public ArrayList<T> (int page, int count)  throws SQLException;
    public T Get(int key)  throws SQLException;
    public void Insert(T model) throws IllegalAccessException;
    public void Update(T model);
    public void Delete(int id);
}

这一行public ArrayList<T>给了我一个编译器错误error: <identifier> expected public ArrayList<T> (int page, int count) throws SQLException;

您能否帮助我理解它,因为在看来确实有效的课程中? 例如,如果我摆脱了界面中的这一行,并且有了这个类,它将编译成功:

public class MySqlRepository<T> implements IRepository<T> {
//[...]
//@Override -- no longer override
public ArrayList<T> GetAll(int page, int count) throws SQLException{
    //"SELECT * FROM {table} LIMIT " + count + " OFFSET " + offset + ";"
    int offset = page * count;
    StringBuilder sqlBuilder = new StringBuilder();

    sqlBuilder.append("Select FROM ")
        .append(modelClass.getName().toLowerCase())
        .append("s ")
        .append("LIMIT ")
        .append(count)
        .append(" OFFSET ")
        .append(offset)
        .append(";");

    ResultSet set = sqlConnection.createStatement().executeQuery(sqlBuilder.toString());

    ArrayList<T> resultList = new ArrayList<>();

    while(set.next())
    {
        resultList.add(createFromCurrentLine(set));
    }
    return resultList;
}
//[...]
}

当我可以在类中使用泛型时,为什么不能在接口的ArrayList返回类型中使用泛型?

1 个答案:

答案 0 :(得分:1)

您仅指定此方法采用的返回类型和参数。 public ArrayList<T> (int page, int count) throws SQLException;。但是,您在哪里指定方法的名称?

由于缺少该方法的名称,因此会出现此编译时错误。

仅需注意几个要点:

  • 您应返回java.util.List而不是特定类型(java.util.ArrayList
  • 您不需要在接口名称前加上I。这是C#中遵循的约定
  • Java中的方法名称最好以小写字母开头(并跟随camel-case notation)。