I am coming from a C++ background. I use vector push_back and pop_back methods to push and pop out elements from the vector. I know arraylist is sort of equivalent to vector, but I don'f find equivalent methods to push_back and pop_back in arraylist API. The closet I could find is LinkedList. Am I missing something or is there any other equivalent to vector in C++?
Any help is appreciated.
4 Answers
Use add() from ArrayList to push_back.
For pop_back you have to play around a bit more with indexes and remove().
Let's look at this example:
// push_back equivalent
ArrayList<int> a = new ArrayList<int>();
a.add(2); // Add element to the ArrayList.
a.add(4);
// pop_back equivalent.
a.remove(a.size()-1); // Remove the last element from the ArrayList.
Use ArrayList for dynamically add and remove element.
For push_back() use .add()
add() method to add elements in the list
List<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(10);
For pop_back() use .remove()
remove() used for removing the element at the specified position in this list. So, pass last index in method to delete last element
arrlist.remove(arrlist.size() - 1);
You can use add() for push_back() and remove() for pop_back().
ArrayList<data_type> data = new ArrayList<data_type>();
data.add(value1);
data.add(value2);
data.remove(data.size() - 1);
P.S : arraylist is a container not API.
We can use the LinkedList<E> data structure
Adding at the end by: add(E e)
removing at the end by using: pollLast()
Example:
package test;
import java.util.*;
public class test{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("element1");
al.add("element2");
al.add("element3");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.print(itr.next()+" ");
}
System.out.println(" ");
al.add("element4");
itr=al.iterator();
while(itr.hasNext()){
System.out.print(itr.next()+ " ");
}
System.out.println(" ");
//pop_back
al.pollLast();
itr=al.iterator();
while(itr.hasNext()){
System.out.print(itr.next()+" ");
}
}
}
result:
element1 element2 element3
element1 element2 element3 element4
element1 element2 element3