您好,欢迎来到测品娱乐。
搜索
您的当前位置:首页检查数组中的重复值

检查数组中的重复值

来源:测品娱乐

在这里,我附上了一个Java示例,展示了如何检查数组中的重复值。 我展示了两种方法来实现此目的。

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

2)使用HashSet检测重复值。 – 40行

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

 

package com.mkyong;

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)
	{
		Set
   
   
    
     sValueSet = new HashSet
    
    
     
     ();
		for(String tempValueSet : sValueTemp)
		{
			if (sValueSet.contains(tempValueSet))
				return true;
			else
				if(!tempValueSet.equals(""))
					sValueSet.add(tempValueSet);
		}
		return false;
	}
	
	
}




    
    
   
   

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- cepb.cn 版权所有 湘ICP备2022005869号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务