猿问

在单个方法中创建和使用 ArrayList?

是否可以ArrayList在方法内创建和使用一个?我想在public int min()方法中创建一个临时堆栈来跟踪最小值。但是,编译器抱怨 ArrayListadd()方法:Cannot resolve method 'add(int)'我认为这是因为我试图在创建ArrayList?


import java.util.*;


public class MinStack {

private ArrayList<Integer> data;



public MinStack() {

    data = new ArrayList<Integer>();

}


public void push( int a ) {

    data.add( a );

}


public int pop() {

    if ( data.size() <= 0 ) {

        throw new IllegalStateException();

    }

    return data.remove( data.size() - 1 );

}


public int size() {

    return data.size();

}


public int min() {

    MinStack smalls = new MinStack();

    int elMin = (data.get((data.size() - 1)));

    smalls.add(elMin);

    while (!data.isEmpty()) {

        if (data.get(data.size() - 1) < elMin)

        elMin = data.get(data.size() - 1);

    }

    return elMin;

}


慕姐8265434
浏览 190回答 3
3回答

30秒到达战场

您不是add在 的实例上调用方法,Arraylist而是在MinStack没有add方法的类对象的实例上调用它。您应该调用push方法,因为它是在您的类中定义的,它将调用add数组列表的方法。或者method在MinStack类中定义/重命名(推送)一个名称add

慕田峪7331174

您使用了不正确的设计策略来实现此类。他们在你的实现中有很多流程,在这里我不打算谈论这些。在你的设计方法中,而不是push()在你的类中调用实现的行为调用。您正在尝试调用一个在此类中未实现的方法,称为add().&nbsp;如果你想在类中使用你的实现行为,只需调用你的方法作为smalls.push(elMin)instated of&nbsp;smalls.add(elMin)。

呼啦一阵风

我认为你可以这样做:public int min() {&nbsp; &nbsp; if(data.isEmpty())&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("the list is empty...");&nbsp; &nbsp; int elMin = data.get(0);&nbsp; &nbsp; for(int i : data) {&nbsp; &nbsp; &nbsp; &nbsp; if(i < elMin) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elMin = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return elMin;}
随时随地看视频慕课网APP

相关分类

Java
我要回答