萌新角度看java
老规矩,想说的都在代码块里:
public class MyFanShe {
//Set集合
//传入的对象不能有重复值
//常用实现类:HashSet与TreeSet。此外还有:EnumSet和LinkedHashSet。
//以下为HashSet的一些应用
public static void main(String[] args) {
HashSet<Object> hashSet = new HashSet<>();
HashSet<Object> hash_test = new HashSet<>();
HashSet<Object> test = new HashSet<>();
for (int i = 0; i < 10; i++) {
test.add(i);
}
hashSet.add("asd");//add():将指定的元素添加到集合中
for (int i = 0; i < 10; i++) {
hashSet.add(i);
}
hash_test.addAll(hashSet);//addAll():将指定集合的所有元素添加到集合中
hash_test.add(312);
System.out.println(hashSet);//输出顺序不定
System.out.println(hash_test);
hash_test.remove(312);//remove():从集合中移除指定的元素
System.out.println(hash_test);
hash_test.add(312);
hash_test.removeAll(hashSet);//removeAll():从存在于另一个指定集合中的集合中删除所有元素
System.out.println(hash_test);
System.out.println("返回集合的长度:" + hash_test.size());//size():返回集合的长度(元素个数)
hash_test.clear();//clear():从集合中删除所有元素
System.out.println("clear后的hash_test:" + hash_test);
hash_test.addAll(hashSet);
System.out.println("是否包含指定元素" + hash_test.contains(312));//contains():集合包含指定的元素则返回true
System.out.println("是否包含指定集合内的所有元素" + hash_test.containsAll(hashSet));//containsAll():如果集合包含指定集合的所有元素,则返回true
System.out.println("返回哈希码值(集合中元素的地址):" + hash_test.hashCode());//hashCode():返回哈希码值(集合中元素的地址)
System.out.println("返回包含集合中所有元素的数组" + hash_test.toArray());//toArray():返回包含集合中所有元素的数组
}
//还有几个不是很懂的:
//iterator():返回一个迭代器,该迭代器可用于顺序访问集合中的元素
//keepAll():保留集合中所有还存在于另一个指定集合中的所有元素
//retainAll():(不是很确定)上面的keepAll()不能直接用,这个可以
}
附上运行结果: