日期:2014-05-20 浏览次数:20739 次
import java.util.*; public class test { public static void main(String []args){ ArrayList<String> list = new ArrayList<String>(); list.add("how"); list.add("are"); list.add("you"); doubleList(list); System.out.print(list.toString()); } public static void doubleList(ArrayList<String> list){ for(int i = 0; i<list.size(); i++){ list.add(i*2,list.get(i*2) ); } } }
/** * Checks if the given index is in range. If not, throws an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. */ private void RangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); }
------解决方案--------------------
for(int i = 0; i<list.size(); i++){
list.add(i*2,list.get(i*2) );
原排列 0 1 2
要加到 3 4 5 位
可程序中写成加到 0 2 4(注意 list.get(4)时候溢出。)
int size = list.size(); //计算原list大小。
使用list.add(i+size,list.get(i));
------解决方案--------------------
public static void doubleList(ArrayList<String> list){
for(int i = 0; i<list.size(); i++){
list.add(i,list.get(i) );
list.add(i+1,list.get(i) );
}
}
这样不行吗?
------解决方案--------------------
这是根据楼主的意思实现的代码,请参考
import java.util.*; public class Test{ public static void main(String []args){ ArrayList<String> list = new ArrayList<String>(); list.add("how"); list.add("are"); list.add("you"); doubleList(list); System.out.print(list.toString()); } public static void doubleList(ArrayList<String> list){ String[] strAry=new String[list.size()]; list.toArray(strAry); // for(String s:strAry){ // System.out.println(s); // } for(int i = 0; i<strAry.length; i++){ list.add(i*2,strAry[i] ); } } }
------解决方案--------------------