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

Java中ArrayList指定自定义类类型报错:无法解析类型求助

Hey there! Let's break down what's causing that error and fix it up for you.

The Root of the Problem

The error "Cannot resolve Name to a Type" happens because you're using getraenk as the generic type for your ArrayList—but that's the name of a String variable in your class, not the custom Drinks (or German Getraenk) class you mentioned. Java generics require a valid class/interface type name, not a variable name, so the compiler can't find a type called getraenk.

Step-by-Step Fixes

  1. Create your custom Getraenk class (since you mentioned you have a Drinks-like custom class). Remember Java class names use PascalCase (first letter uppercase):

    public class Getraenk {
        private String name;
        // Add other properties you need, like price (preis)
        
        public Getraenk(String name) {
            this.name = name;
        }
    
        // Optional: Add getter/setter methods
        public String getName() {
            return name;
        }
    }
    
  2. Fix the ArrayList generic type in your KellnerGetraenkeliste class—replace the lowercase getraenk (variable name) with uppercase Getraenk (your class name):

  3. Make your constructor public (right now it's private, so you can't create instances of KellnerGetraenkeliste from outside the class).

Corrected Full Code

Here's the updated KellnerGetraenkeliste class:

import java.util.ArrayList;

public class KellnerGetraenkeliste {
    // Class attributes
    private String kunde;
    private int anzahl;
    private String getraenk; // This is your String variable, keep it lowercase

    // Public constructor to allow instantiation
    public KellnerGetraenkeliste(String kunde, int anzahl, String getraenk) {
        super();
        this.kunde = kunde;
        this.anzahl = anzahl;
        this.getraenk = getraenk;
    }

    // Fixed generic type: uses your custom Getraenk class
    ArrayList<Getraenk> getraenkeListe = new ArrayList<>();
}

Bonus: Better OOP Practice

If you want to store actual Getraenk objects instead of just their names in your KellnerGetraenkeliste class, you can update the getraenk attribute to use the Getraenk type directly:

// Replace private String getraenk; with:
private Getraenk getraenk;

// Update the constructor to accept a Getraenk object:
public KellnerGetraenkeliste(String kunde, int anzahl, Getraenk getraenk) {
    super();
    this.kunde = kunde;
    this.anzahl = anzahl;
    this.getraenk = getraenk;
}

Just make sure the Getraenk class is in the same package as KellnerGetraenkeliste, or add an import statement if it's in a different package.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:05:32