You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RandomUniformTileGenerator类属性赋值类型不匹配及List无法实例化问题求助

问题分析与解决方案

咱们先拆解你遇到的两个核心问题,再一步步给出修正方案:

1. 类型不匹配错误

你在RandomUniformTileGenerator的构造函数里,直接把单个UniformTile实例赋值给了声明为List<Tile>的tiles属性——系统期望的是一组Tile的集合,但你传入了单个Tile对象,这就触发了类型不匹配的报错。

2. List接口无法直接实例化

List是Java中的抽象接口,确实不能用new List<>()直接创建实例,得用它的具体实现类,比如ArrayList、LinkedList这类常用的实现。


修正后的完整代码

下面是针对问题的修正版本,我添加了注释说明关键改动点:

package model;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomUniformTileGenerator implements TileGenerator{
    private final List<Tile> tiles;
    private final Random randomGenerator;

    public RandomUniformTileGenerator(List<Color> colors, Random randomGenerator){
        // 1. 用List的具体实现类ArrayList实例化tiles,解决接口无法直接实例化的问题
        this.tiles = new ArrayList<>();
        this.randomGenerator = randomGenerator;

        // 2. 遍历传入的颜色列表,为每个颜色创建对应的UniformTile并加入集合
        // 注意:原代码中colors.get(colors.size())会触发索引越界,这里改为遍历每个颜色
        for(Color color : colors){
            ColoredSide coloredSide = new ColoredSide(color);
            UniformTile tile = new UniformTile(coloredSide);
            this.tiles.add(tile);
        }
    }

    public Tile nextTile(Square square){
        // 新增空集合判断,避免后续调用时出现索引越界异常
        if(this.tiles.isEmpty()){
            throw new IllegalStateException("No tiles available to generate");
        }
        return this.tiles.get(randomGenerator.nextInt(tiles.size()));
    }
}

额外细节说明

我还修正了原代码里一个潜在的致命bug:colors.get(colors.size())会直接抛出IndexOutOfBoundsException——因为List的索引从0开始,最大有效索引是size()-1,用size()作为索引必然越界,所以改成了遍历每个颜色来生成对应的Tile。

这样改动后,既解决了类型不匹配和接口无法实例化的问题,也避免了潜在的运行时异常。

内容的提问来源于stack exchange,提问作者Togo_Yan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:27:39