测试通过(数组长度20000时,耗时不到1s public class HashSetTest { public static void main(String[] args) { String[] list = new String[]{"aa","bbb","cc","dd","aa","ee","ff","cc"}; HashSet set = new HashSet(); for (int i = 0; i < list.length; i++) { if (set.contains(list[i])) { System.out.println(list[i] + " is already in the array"); break; } else set.add(list[i]);
HashSet set = new HashSet();
set.add(数组);
if(set.size()<length)
//就一定有重复值
其实还有更加快速的方法。
就是把他们的HashCode放入HashSet。
通常我觉得数据不上100,显式不出来好处。反而不如两个循环来得快速。
public class HashSetTest { public static void main(String[] args) {
String[] list = new String[]{"aa","bbb","cc","dd","aa","ee","ff","cc"};
HashSet set = new HashSet();
for (int i = 0; i < list.length; i++)
{
if (set.contains(list[i]))
{
System.out.println(list[i] + " is already in the array");
break;
}
else
set.add(list[i]);
} }
}