写在开头:本文用于作者学习Java常用API
我将官方文档中HashSet 1.6版本中类中所有API全测了一遍并打印了结果,日拱一卒,常看常新
add()
@Test
public void test_add(){
HashSet<String> hashSet = new HashSet<>();
// 添加元素到HashSet中
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
System.out.println(hashSet);//[Apple, Orange, Banana]
}
clear()
@Test
public void test_clear(){
// 清空HashSet中的元素
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.clear();
System.out.println(hashSet);//[]
}
clone()
@Test
public void test_clone(){
//返回此 HashSet 实例的浅表副本:并没有复制这些元素本身
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
Object clone = hashSet.clone();
System.out.println(clone);//[Apple, Orange, Banana]
}
contains()
@Test
public void test_contains(){
//判断此 HashSet是否包含指定元素
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
boolean contains = hashSet.contains("apple");
System.out.println(contains);//false
boolean contains1 = hashSet.contains("Apple");
System.out.println(contains1);//true
}
isEmpty()
@Test
public void test_isEmpty(){
//判断此 HashSet是否为空
HashSet<String> hashSet = new HashSet<>();
System.out.println(hashSet.isEmpty());//true
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
System.out.println(hashSet.isEmpty());//false
}
iterator()
@Test
public void test_iterator(){
//返回此 HashSet的迭代器
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
Iterator<String> iterator = hashSet.iterator();
while(iterator.hasNext()){
String next = iterator.next();
System.out.println(next);
/*Apple
Orange
Banana
*/
}
}
remove()
@Test
public void test_remove(){
//若指定元素存在,则移除,返回true。不存在,返回false
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
boolean apple = hashSet.remove("Apple");
System.out.println(apple);//true
boolean egg = hashSet.remove("Egg");
System.out.println(egg);//false
}
size()
@Test
public void test_size(){
//返回该hashSet的大小
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
System.out.println(hashSet.size());//3
}
toArray()
@Test
public void test_toArray(){
//将hashSet转成数组
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
Object[] array = hashSet.toArray();
System.out.println(Arrays.toString(array));//[Apple, Orange, Banana]
}