把数组中的元素取出放入一个HashSet中,这样就可以过滤重复的值了。
用hashset 重复的自动去掉了HashSet hashset=new HashSet();hashset。add(1);都加进去Iterator iterator=hashset。itertaor();做一个while循环 输出就ok了
-------------------------------------------------
如果你要得到的数组可以无序的话将原数组里的元素放到HashSet中就行了,如果你想得到的数组还要之前的顺序的话,就只能一个个比了,从头开始遍历,看每个元素跟它前面的元素有没有重复有则删掉。
-----------------------------------------------------
Integer str[] = {1,2,3,3,3,4}; Set <Integer>set=new TreeSet<Integer>(Arrays.asList(str)); Integer[] newArray=set.toArray(new Integer[set.size()]) ; for(Integer i:newArray){ System.out.println(i); } //System.out.println(set);
--------------------------------------------
private static int [ ] supRep( int [ ] x) { int[] tempArray = new int[x.length]; boolean repeated = false; int nbNonRep=0; //Verify for each element for (int i=0; i<x.length; i++){ for (int j=i+1; j<x.length; j++){ if (x[i]==x[j]){// x[i] is repeated repeated = true; break; } } if (repeated == false){// a non repeated number tempArray[nbNonRep++]=x[i]; } repeated = false; } int[] resultArray = new int[nbNonRep]; System.arraycopy(tempArray, 0, resultArray, 0, nbNonRep); return(resultArray); } public static void main(String[] args) { int [ ] arr = new int[]{2,5,6,6,8,12,3,5}; int [] a = supRep(arr); for (int i = 0; i<a.length; i++){ System.out.print(a[i]+ " "); } } -------------------------------------------------------------------------测试结果:run:2 6 8 12 3 5 成功生成(总时间:0 秒) -------------------------------------------------------------------------当然,我是用两个两个数比较的,如果数据量非常大,比如几万几十万或者更多数字,最好做一个Tree,这样浏览一遍你的Array就OK了 -------------------------------------------------------------------------如果想要简单,用ArrayList就可以了: ArrayList myList = new ArrayList(); for (int i=0; i<arr.length; i++){ if (!myList.contains(arr[i])) myList.add(arr[i]); } for (int i = 0; i<myList.size();i++){ System.out.print(myList.get(i) + ", "); }不过程序效率肯定是不高的 ArrayList:底层用数组实现的List 。特点:查询效率高,增删效率低 轻量级 线程不安全。HashSet:采用哈希算法来实现Set接口, 唯一性保证:重复对象equals方法返回为true ,重复对象hashCode方法返回相同的整数不同对象 哈希码 尽量保证不同(提高效率)。TreeMap:集合是指一个对象可以容纳了多个对象(不是引用),这个集合对象主要用来管理维护一系列相似的对象。