【问题标题】:Error: cannot add csv to Java array using lombok错误:无法使用 lombok 将 csv 添加到 Java 数组
【发布时间】:2022-01-04 16:06:56
【问题描述】:

我正在尝试将现有 csv 文件中的数据添加到 java 数组,但我似乎没有找到解决方法。

这是我多次尝试后遇到的错误。 错误:无法为最终变量 addPlatform 赋值 addPlatform = new ArrayList();

这是我的 main.java

public class Game {
    public static void main(String[] args) {
        Game game = new Game("platforms.csv");
        game.run();
    }

@Getter(lazy = true)
    private final List<Platform> addPlatform = new ArrayList<Platform>();
    /**
     * Reads platforms from csv file and returns the as list.
     * @return platforms - Platforms as list
     */
    private List<Platform> readPlatforms() {
        if (addPlatform == null) {
            addPlatform = new ArrayList<Platform>();
        }

        return addPlatform;

    }

平台.java

package com.nortal.platformer;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class Platform {

    private Integer index;
    private Integer cost;
}

平台.csv

index, cost
0, 100
1, 200
2, 400

【问题讨论】:

  • 我有一个 Game.java 类和一个文件platforms.csv。我正在尝试将 csv 文件中的所有行添加到列表中(在 Game.java 中)``` /** * 从 csv 文件中读取平台并将它们作为列表返回。 * @return 平台 - 平台列表 */ private List readPlatforms() { return addPlatform; } ```

标签: java arrays collections lombok


【解决方案1】:

final 变量不能被赋予新值。这些值仅在声明期间或构造函数中分配。

像这样改变你的班级:

如果您需要为 addPlatform 赋值,那么它不能是最终的 - 这意味着您必须删除 lazy=true 并在没有 final 的情况下实现自己的惰性初始化。

最简单的实现是


    private List<Platform> addPlatform;

    public synchronized List<Platform> getAddPlatform(){
        if (addPlatform == null) {
            addPlatform = new ArrayList<Platform>();
        }

        return addPlatform;
    }

【讨论】:

  • 这是我得到的错误:error: not a statement this.addPlatform;
  • 该错误自行解释。根据设计,final 变量一旦创建就不能“重新分配”。
  • 仍然有一些错误,索引 0 超出了长度 0 的范围。让我解释一下我要做什么,我正在尝试将 csv 文件中的值添加到列表中然后返回列表中的值,但当前不起作用
  • 问题不清楚 - 请提供最小的可重现代码。 stackoverflow.com/help/minimal-reproducible-example
  • 我有一个 Game.java 类和一个文件platforms.csv。我正在尝试将 csv 文件中的所有行添加到列表中(在 Game.java 中)``` /** * 从 csv 文件中读取平台并将它们作为列表返回。 * @return 平台 - 平台列表 */ private List readPlatforms() { return addPlatform; } ```
【解决方案2】:

这种情况下的问题是双重的:

  • 在 readPlatform 中,您正在创建一个新的 ArrayList,并尝试将其分配给最终字段
  • 如果您使用@Getter(lazy=true),lombok 将生成完全不同的数据结构,因此addPlatform 的类型不再是List&lt;Platform&gt;

我不知道为什么在这种情况下您使用惰性 getter,因为初始化代码的计算成本既不高也不占用大量内存。所以在你的情况下,我会写:

@Getter
final private List<Platform> = new ArrayList<>();

访问 final 字段本身始终是线程安全的。

但由于您还在代码中使用了synchonized,我认为您不应该使用ArrayList,而应该使用CopyOnWriteArrayList

@Getter
final private List<Platform> = new CopyOnWriteArrayList<>();

使用 lombok 的 @Getter(lazy=true) 注释的字段必须是最终的,这允许 lombok 重写整个底层代码。获取内容的唯一受支持方法是通过 getter。此外,惰性 getter 确实内置了自己的线程安全性。因此不需要整个同步块。

披露:我是 Project Lombok 开发人员。

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多