+ 1
Java.arraylist problem
I don’t know how to add element after the number. Which add() should i use? Like this example: Push front(5): ( I did this method) Output:5 Push back (4) ( here I have problem) Output: 5 4
2 Respuestas
+ 2
All methods of Java's java.util.ArrayList class are documented here:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
This add method adds to the end of the list:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-
This adds at an arbitrary index:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-int-E-
Here is a little example:
ArrayList<Integer> yourlist = new ArrayList<Integer>();
yourlist.add(0, 4); // adds to beginning. index 0 is the beginning.
yourlist.add(5); // adds to the end.
I would implement with both of those.
Not exactly your question but if I was concerned at all with efficiency and needed to frequently add to the beginning and end of a container without randomly accessing elements elsewhere in the container, I'd use Java's java.util.LinkedList instead of an ArrayList. ArrayList is efficient for adding to one end where no elements need to be moved but inserting on the other requires shifting all elements. A linked list is equally efficient on both ends but is just inefficient for randomly accessing elements somewhere near the middle of the list.
0
use ListIterator, then you could reverse iterate:
public void print() {
ListIterator list = l.listIterator(l.size());
while (list.hasPrevious()) {
System.out.println(list.previous());
}
}