Write a Program To Check Unique Number in Java

You are to write a program to check unique number in Java

import
java.util.*;
import java.io.*;

public class IsUnique
{
public static boolean
isUniqueUsingHash(String word)
{c
har[] chars = word.toCharArray();

Set<Character> set = new
HashSet<Character>();
for (char c : chars)

if (set.contains(c))
return false;
else
set.add(c);
return true;
}

public static boolean
isUniqueUsingSort(String word)
{c
har[] chars = word.toCharArray();

if (chars.length <= 1)
return true;
Arrays.sort(chars);

char temp = chars[0];
for (int i = 1; i < chars.length; i++)
{

if (chars[i] == temp)
return false;
temp = chars[i];
}

return true;
}

public static void main(String[] args)
throws IOException
{
System.out.println(isUniqueUsingHash("? "Unique" : "Not Unique");
System.out.println(isUniqueUsingSort("? "Unique" : "Not Unique");

}
}

Output:

Unique

Not Unique

Java Tips

Relevant Reading

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.