Ok , here is my problem . I'm learing to use generic classes and methods. I want to make an generic array list and method that will add/remove element by choosen index. I simply doesn't know how to do that . My example is calling an IndexOutOfBoundsException.
Any help is welcome. Thanks it advance .
class klasa3:
public class klasa3<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
public klasa3(int initSize){
}
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o,int indeks) {
o = list.get(indeks);
list.add(o);
}
public E pop(int indeks) {
E o = list.get(indeks);
list.remove(indeks);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
return "stack: " + list.toString();
}
}
main class:
public class klasa2 {
public static void main(String[] args ) {
klasa3 stak2 = new klasa3(13);
stak2.push("cola",2); // problem here
stak2.pop(2);
System.out.println(stak2.getSize());
}
}
You're creating an empty ArrayList
, and then trying to get the third element (element at index 2) from it within your push
method. That's not going to work.
Now, you're currently ignoring your initSize
parameter in your constructor. You might want something like:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize) {
for (int i = 0; i < initSize; i++) {
list.add(null);
}
}
Or provide a default element:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize, E element) {
for (int i = 0; i < initSize; i++) {
list.add(element);
}
}
See more on this question at Stackoverflow