Set ใช้เก็บค่าที่ไม่ซ้ำกัน (unique) เท่านั้น ไม่เก็บค่าซ้ำ เมื่อสร้าง HashSet จะ implement HashMap ภายใน ใช้เมธอด add() เพิ่ม element ซึ่งภายในจะเรียก put() ของ HashMap ดังนั้น Set เก็บค่า unique ด้วย HashMap
HashMap เก็บ key-value pairs ที่ unique ใช้ put() แทรก คืนค่า previous value ที่เกี่ยวกับ key หรือ null ขึ้นอยู่กับว่ามี mapping สำหรับ key นั้นอยู่แล้วหรือไม่
LinkedHashSet extends HashSet เรียก constructor ของ HashSet ด้วย super()
ตัวอย่าง
import java.util.HashSet;
public class Demo {
public static void main(String args[]) {
HashSet my_hashset = new HashSet();
boolean my_b1 = my_hashset.add("only");
boolean my_b2 = my_hashset.add("sample");
boolean my_b3 = my_hashset.add("sample");
System.out.println("The value of first boolean is " + my_b1);
System.out.println("The value of second boolean is = " + my_b2);
System.out.println("The value of third boolean is = " + my_b3);
System.out.println(my_hashset);
}
}
ผลลัพธ์
The value of first boolean is true The value of second boolean is = true The value of third boolean is = false [only, sample]
คลาส Demo มี main สร้าง HashSet เพิ่ม "only" (true), "sample" (true), "sample" อีกครั้ง (false เพราะซ้ำ) แสดงค่า boolean และเนื้อหา set