Is it possible to create and use an ArrayList within a method? I would like to create a temporary stack in the public int min() method to track the smallest value. However, the compiler complains about the ArrayList add() method: Cannot resolve method 'add(int)' I presume that's because I'm trying to run it inside the same method that created the 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;
}
push!=add.ArrayList, or anything at all, “within a method”? Besides that, if all you want to use, is pushing and popping, you may use anArrayDequeinstead.