0
    final int NUM_OF_SERVERS = 2;

    List<Database> databases = new ArrayList<Database>();

    for (int i = 1; i < NUM_OF_SERVERS; i++){

        Database database = new Database("server" + i + ".txt");
        databases.add(database);

    }

    List<Server> servers = new ArrayList<Server>();

    for (int i = 1; i < NUM_OF_SERVERS; i++){

        **Server server = new Server(databases[i-1]);** //the error is here
    }

我有一个数据库列表,我想使用数据库列表的元素作为构造函数的参数来创建一个服务器列表,但它会引发此错误:“表达式的类型必须是数组类型,但它解析为列表”将鼠标悬停在突出显示的行上时。

4

1 回答 1

3

问题是那databasesList<Database>- 而不是Database[]. 因此表达式databases[i-1]无效。这与您调用构造函数这一事实无关 - 这与您访问列表中元素的方式无关。你要databases.get(i - 1)

for (int i = 1; i < NUM_OF_SERVERS; i++) {
    Server server = new Server(databases.get(i-1));
    // Presumably do something with server here
}

不过,在我看来,您遇到了一个错误的错误-您最终只会得到NUM_OF_SERVERS - 1服务器。我怀疑你会更好:

final int NUM_OF_SERVERS = 2;

List<Database> databases = new ArrayList<Database>();

// Note the change to starting index
for (int i = 0; i < NUM_OF_SERVERS; i++) {
    Database database = new Database("server" + i + ".txt");
    databases.add(database);
}

List<Server> servers = new ArrayList<Server>();
// Note the change to starting index *and* the use of i rather than i - 1 
for (int i = 0; i < NUM_OF_SERVERS; i++) {
    Server server = new Server(databases.get(i));
    // Use server here
}

或者更好的是,为第二个循环使用增强的 for 循环:

for (Database database : databases) {
    Server server = new Server(database);
    // Use server here
}
于 2013-04-14T14:55:33.197 回答