简体   繁体   English

如何将 Arraylist 的最后 3 个元素添加到不同的 Arraylist?

[英]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.但是,我想将最后 3 个元素添加到不同的数组列表中。 Is there a way, where I can transfer just the last three elements of the arraylist #1 to arraylist #2.有没有办法,我可以只将 arraylist #1 的最后三个元素传输到 arraylist #2。 Here is my regex data in arraylist #1.这是我在 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(from, to)方法。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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