位置:首页 > 易百教程 > Java检查数组中的重复值

Java检查数组中的重复值

在这里,附上一个Java的例子来说明如何在数组中检查重复值。这里展示两种方法来实现这一点。

1) 使用两个for循环比较数组中的每个值 - 21

2)使用 HashSet 检测重复的值 - 第40行

希望对你有所帮助,如果知道在数组中比较重复值的任何其他方法,请分享给我们。

 
package com.yiibai;

import java.util.Set;
import java.util.HashSet;

public class CheckDuplicate
{
	public static void main(String args[])
	{
		String [] sValue = new String[]{"a","b","c","d","","","e","a"};
		
		if(checkDuplicated_withNormal(sValue))
			System.out.println("Check Normal : Value duplicated! \n");
		if(checkDuplicated_withSet(sValue))
			System.out.println("Check Set : Value duplicated! \n");
		
	}
	
	//check duplicated value
	private static boolean checkDuplicated_withNormal(String[] sValueTemp)
	{
		for (int i = 0; i < sValueTemp.length; i++) {
			String sValueToCheck = sValueTemp[i];
			if(sValueToCheck==null || sValueToCheck.equals(""))continue; //empty ignore
			for (int j = 0; j < sValueTemp.length; j++) {
					if(i==j)continue; //same line ignore
					String sValueToCompare = sValueTemp[j];
					if (sValueToCheck.equals(sValueToCompare)){
							return true;
					}
			}

		}
		return false;
		
	}
	
	//check duplicated value
	private static boolean checkDuplicated_withSet(String[] sValueTemp)
	{
		SetsValueSet = new HashSet();
		for(String tempValueSet : sValueTemp)
		{
			if (sValueSet.contains(tempValueSet))
				return true;
			else
				if(!tempValueSet.equals(""))
					sValueSet.add(tempValueSet);
		}
		return false;
	}
	
	
}


标签:Java    检查    数组    重复值