簡體   English   中英

我不能完全讓我的通用類在Java中工作

[英]I can't quite get my generic class to work in Java

我執行以下包含三個方法的執行。 plus將字符串添加到類中, minus將其刪除,並進行empty檢查,如果沒有更多的字符串存儲,則返回true。

private static void test() {
    Stack<String> stack = new Stack<String>();
    stack.plus("hello1");
    stack.plus("hello2");
    stack.plus("hello3");
    stack.plus("hello4");

    while (!stack.empty()) {
        System.out.println(stack.minus());
    }

    stack.plus("a1");
    stack.plus("a2");
    stack.plus("a3");
    stack.plus("a4");
    stack.minus();
    stack.minus();
    stack.plus("a5");
    stack.plus("a6");

    while (!stack.empty()) {
        System.out.println(stack.minus());
    }
}

@SuppressWarnings("hiding")
public class Stack<String> {

    private String e;

    public void plus(String e) {
        this.e= e;
    }

    public String minus() {
        return e;   
    }

    public boolean empty() {
        if(e != null) {
        }return false;
    }
}

輸出應為:

hello4

hello3

hello2

hello1

A6

A5

a2

A1

目前,我的程序一直在“ hello4”處無限循環,我還不太清楚如何解決empty函數。 我懷疑該方法是我的主要問題。

您似乎誤解了泛型的語法。 在您的Stack類中,通用參數String行為更像是一個變量,而不像String類。

//DataType is substituted for whatever you tell it in <...> when making a Stack object
public class Stack<DataType> { 

    private List<DataType> memory = new ArrayList<>();

    public void push(DataType e) {
        memory.add(e);
    }

    public DataType pop() {
        if(memory.isEmpty())
           return null;
        int lastIndex = memory.size()-1;
        DataType element = memory.get(lastIndex); //get last element of memory
        memory.remove(lastIndex); //remove it from the stack
        return element; //return it   
    }

    public boolean isEmpty() {
        return memory.isEmpty();
    }
}

您可以像現在已經使用的那樣使用它:

Stack<String> stack = new Stack<String>(); //DataType in Stack becomes String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM