例如,如果我想保留首先出现的字符串的顺序,但我还希望第二次出现的重复项跟在输出列表中的第一个之后。例如,如果我添加: arrlist.add("bob"); arrlist.add("pat"); arrlist.add("tan"); arrlist.add("鲍勃"); arrlist.add("垫子"); arrlist.add("猫"); arrlist.add("狗"); arrlist.add("猫");
我希望输出是
String = bob
String = bob
String = pat
String = tan
String = mat
String = cat
String = cat
String = dog
这是我的代码:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<String> arrlist = new ArrayList<String>();
// use add() method to add elements in the list
arrlist.add("bob");
arrlist.add("pat");
arrlist.add("tan");
arrlist.add("bob");
arrlist.add("mat");
arrlist.add("cat");
arrlist.add("dog");
arrlist.add("cat");
// let us print all the elements available in list
for (String number : arrlist) {
System.out.println("String = " + number);
}
// retrieves element at 4th postion
String retval=arrlist.get(3);
System.out.println("Retrieved element is = " + retval);
}
}