简体   繁体   中英

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM