Java Generics 简明教程
Java Generics - Set
Java 已在 Set 接口中提供了泛型支持。
Java has provided generic support in Set interface.
Syntax
Set<T> set = new HashSet<T>();
其中
Where
-
set − object of Set Interface.
-
T − The generic type parameter passed during set declaration.
Description
T 是传递给 Set 泛型接口及其实现类 HashSet 的类型参数。
The T is a type parameter passed to the generic interface Set and its implemenation class HashSet.
Example
使用任意你选择的编辑器创建以下 Java 程序。
Create the following java program using any editor of your choice.
package com.tutorialspoint;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class GenericsTester {
public static void main(String[] args) {
Set<Integer> integerSet = new HashSet<Integer>();
integerSet.add(Integer.valueOf(10));
integerSet.add(Integer.valueOf(11));
Set<String> stringSet = new HashSet<String>();
stringSet.add("Hello World");
stringSet.add("Hi World");
for(Integer data: integerSet) {
System.out.printf("Integer Value :%d\n", data);
}
Iterator<String> stringIterator = stringSet.iterator();
while(stringIterator.hasNext()) {
System.out.printf("String Value :%s\n", stringIterator.next());
}
}
}
这会产生以下结果 −
This will produce the following result −