java数组删除重复?

时间:2014-04-18 22:49:16

标签: java arrays loops

我尝试通过仅使用循环和扫描程序从用户输入的数组中删除重复项。当我输入数组= {1,2,1}时,我正在尝试不使用任何库方法;程序打印1次。

import java.util.*;

public class Duplicates {
public static void main(String []args) {
    Scanner kb = new Scanner(System.in);

    // The size
    System.out.print("Enter the size of the array: ");
    int n = kb.nextInt();

    // the elements
    System.out.printf("Enter %d elements in the array: ", n);
    int [] a = new int[n];
    for(int i = 0; i < a.length; i++)
        a[i] = kb.nextInt();

    // remove duplicate elements
    for(int i = 0; i < a.length; i++){
        for(int j = i+1; j < a.length; j++){
            if (a[j] != a[i]){
                a[j] = a[i];
                ++j;
            }
            a[j] = a[i];
        }
    }

    // print
    for(int k = 0; k < a.length; k++)
        System.out.print(a[k] + " ");

}
}

谢谢,

1 个答案:

答案 0 :(得分:-1)

如果您使用lang库,则可以从Array中删除元素。

注意:以下源代码来自此链接

来源: http://java67.blogspot.com.au/2012/12/how-to-remove-element-from-array-in-java-example.html

import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

public class RemoveObjectFromArray{

    public static void main(String args[]) {

        //let's create an array for demonstration purpose
        int[] test = new int[] { 101, 102, 103, 104, 105};

        System.out.println("Original Array : size : " + test.length );
        System.out.println("Contents : " + Arrays.toString(test));

        //let's remove or delete an element from Array using Apache Commons ArrayUtils
        test = ArrayUtils.remove(test, 2); //removing element at index 2

        //Size of array must be 1 less than original array after deleting an element
        System.out.println("Size of array after removing an element  : " + test.length);
        System.out.println("Content of Array after removing an object : "
                           + Arrays.toString(test));

    } 

}