How can I add the last 3 elements of an Arraylist to a different Arraylist?

Needyboy2 :

I am making a Turing machine. I have a regex text file of the Turing machine and I have to add data to an arraylist. I successfully added all data to an arraylist. However, I want to add the last 3 elements to a different arraylist. Is there a way, where I can transfer just the last three elements of the arraylist #1 to arraylist #2. Here is my regex data in arraylist #1.

(q0,1)->(q0,1,R)
(q0,0)->(q1,1,R)
(q1,1)->(q1,1,R)
(q1,_)->(q2,_,L)
(q2,1)->(qa,_,L)
q0
qa
qr
Sudhir Ojha :

Use subList(from, to) method.

subList(myList.size()-3, myList().size());

For example:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
List<Integer> lastThree = list.subList(list.size()-3, list.size());
System.out.println("All element ="+list);
System.out.println("Last three element ="+lastThree);
list.subList(list.size()-3, list.size()).clear();// will remove last three
System.out.println("After removing last three element="+list);

Output:

All element =[1, 2, 3, 4]
Last three element =[2, 3, 4]
After removing last three element=[1]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334558&siteId=1