当前位置:编程学习 > JAVA >>

Arraylist问题

怎样实现循环将一个已经放好元素的Arrylist对象a1中的元素拿出来放到另一个空对象a2中
并输出a1,a2



例如 a1=[1,2,3,4,5],a2[];
拿出下标1的值放到a2中,
     a1=[1,3,4,5],a2[2];
在拿出下标1的值放到a2中,
     a1=[1,4,5],a2[2,3];
求教大神如何实现 --------------------编程问答-------------------- get(int index) 
          返回此列表中指定位置上的元素。

add(E e) 
          将指定的元素添加到此列表的尾部。


remove(int index) 
          移除此列表中指定位置上的元素。

看api --------------------编程问答-------------------- 这题很简单的,楼上的思路就行了,就是调用两个方法而已,看API --------------------编程问答-------------------- ArrayList<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
a1.add(2);
a1.add(3);
a1.add(4);
a1.add(5);
ArrayList<Integer> a2 = new ArrayList<Integer>();
a2.add(a1.remove(1));
a2.add(a1.remove(1));
--------------------编程问答-------------------- 假设a无限大,我是说要循环放入 --------------------编程问答--------------------

                int index=1;
while(a1.size()>1){
a2.add(a1.remove(index));
}
--------------------编程问答--------------------


        int index=1;
while(a1.size()>index){
a2.add(a1.remove(index));
}
--------------------编程问答--------------------
引用 6 楼 crazypandariy 的回复:


        int index=1;
while(a1.size()>index){
a2.add(a1.remove(index));
}
+1 --------------------编程问答-------------------- 除 --------------------编程问答--------------------

while(a1.size>1){
    a2.add(a1.remove(1));
}

或者

ArrayList a2=new ArrayList(a1);
if(!a2.isEmpty()){
    a2.remove(0);
}
--------------------编程问答-------------------- Collections.copy(a1,a2); --------------------编程问答-------------------- 2楼说的对。。 --------------------编程问答-------------------- 我不循环行吗
直接 a2=a1可以不 --------------------编程问答-------------------- 首先要明白数组跟集合的区别 --------------------编程问答--------------------
public class MySort {

private List<Integer> a1 = null;
private List<Integer> a2 = null;

public MySort() {
a1 = new ArrayList<Integer>();
a2 = new ArrayList<Integer>();
for (int i = 1; i < 6; i++) {
a1.add(i);
}
}

public void doIndex(int index) {
a2.add(a1.get(index));
a1.remove(index);
System.out.print("a1=");
for (int i : a1) {
System.out.print(i + ",");
}
System.out.print("\na2=");
for (int i : a2) {
System.out.print(i + ",");
}
}

public static void main(String[] args) {
MySort ms = new MySort();
for (int i = 0; i <= ms.a1.size(); i++) {
System.out.println("拿出 a1中下标为[1]的值,放入到a2中:");
ms.doIndex(1);
System.out.println();
}
}

} --------------------编程问答-------------------- add()添加就可以了
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,