📅  最后修改于: 2020-10-12 09:42:11             🧑  作者: Mango
Java LinkedHashSet类是set接口的Hashtable和Linked list实现。它继承了HashSet类并实现Set接口。
关于Java LinkedHashSet类的要点是:
LinkedHashSet类扩展了实现Set接口的HashSet类。 Set接口按层次结构顺序继承Collection和Iterable接口。
我们来看一下java.util.LinkedHashSet类的声明。
public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable
Constructor | Description |
---|---|
HashSet() | It is used to construct a default HashSet. |
HashSet(Collection c) | It is used to initialize the hash set by using the elements of the collection c. |
LinkedHashSet(int capacity) | It is used initialize the capacity of the linked hash set to the given integer value capacity. |
LinkedHashSet(int capacity, float fillRatio) | It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument. |
让我们看一下Java LinkedHashSet类的简单示例。在这里,您会注意到元素按插入顺序进行迭代。
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
One
Two
Three
Four
Five
import java.util.*;
class LinkedHashSet2{
public static void main(String args[]){
LinkedHashSet al=new LinkedHashSet();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ajay
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet hs=new LinkedHashSet();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
//Traversing hash table
for(Book b:hs){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
输出:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6