面试题(12)

1—1000 随意去除两个数,放入数组,用代码找出这两个数

package cn.wangbingan.vip;

import java.util.ArrayList;
import java.util.List;

/**
 * 1—1000 随意去除两个数,放入数组,用代码找出这两个数
 * 
 * @author AK
 * 
 */
public class Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<Integer> list1 = new ArrayList<Integer>();
		List<Integer> list2 = new ArrayList<Integer>();
		// 存放1-1000
		for (int i = 0; i <= 1000; i++) {
			list1.add(i);
			list2.add(i);
		}
		// 随即生成两个1-1000的数
		int a = (int) (Math.random() * 1000 + 1);

		int b = (int) (Math.random() * 1000 + 1);

		System.out.println("去除地两个数分别为:" + a + "," + b);

		if (a != b) {
			list2.remove(a);
			list2.remove(b);
			list2.remove(0);
			list1.remove(0);
			for (Integer str : list1) {
				if (!list2.contains(str)) {
					System.out.println("去除的数:" + str);
				}

			}
		}

	}

}

输出结果:

去除地两个数分别为:815,551

去除的数:551

去除的数:815

那么问题来了,如果我往list中添加数据是从1开始的,那结果就不一样了,Why?


你可能感兴趣的:(数据,循环,remove)