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
Create your custom
Getraenkclass (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; } }Fix the ArrayList generic type in your
KellnerGetraenkelisteclass—replace the lowercasegetraenk(variable name) with uppercaseGetraenk(your class name):Make your constructor public (right now it's private, so you can't create instances of
KellnerGetraenkelistefrom 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

