import java.util.*; public class TreeSetDemo { public static void main(String[] args) { //过滤重复元素,但不保证元素的迭代次序 String[] strArray = new String[]{"one", "world ", "one", "dream"}; Set<String> s = new HashSet<String>(); for (int i=0; i<4; i++) if (!s.add(strArray[i])) //添加strArray元素到集合s中 System.out.println("Duplicate detected: " + strArray[i]); System.out.println(s.size() + " distinct words: " + s); //自动按升序排列内容 并过滤掉重复元素 TreeSet<String> treeset=new TreeSet<String>(); treeset.add("b"); treeset.add("a"); 【代码1】: treeset.add("d"); treeset.add("b"); System.out.println("TreeSet:"); System.out.println(treeset); System.out.println("the first element is: "+treeset.first());//返回第一个元素 【代码2】: while(iterator.hasNext()){ System.out.print(iterator.next()+";"); } } }
时间: 2023-06-20 15:05:27 浏览: 131
java代码-import java.util.Scanner;
完整的代码应该是这样的:
```java
import java.util.*;
public class TreeSetDemo {
public static void main(String[] args) {
//过滤重复元素,但不保证元素的迭代次序
String[] strArray = new String[]{"one", "world ", "one", "dream"};
Set<String> s = new HashSet<String>();
for (int i = 0; i < 4; i++)
if (!s.add(strArray[i])) //添加strArray元素到集合s中
System.out.println("Duplicate detected: " + strArray[i]);
System.out.println(s.size() + " distinct words: " + s);
//自动按升序排列内容 并过滤掉重复元素
TreeSet<String> treeset = new TreeSet<String>();
treeset.add("b");
treeset.add("a");
treeset.add("d");
treeset.add("b");
System.out.println("TreeSet:");
System.out.println(treeset);
System.out.println("the first element is: " + treeset.first());
//使用迭代器遍历集合
Iterator<String> iterator = treeset.iterator();
System.out.println("TreeSet Elements:");
while (iterator.hasNext()) {
System.out.print(iterator.next() + ";");
}
}
}
```
运行结果为:
```
Duplicate detected: one
4 distinct words: [dream, one, world ]
TreeSet:
[a, b, d]
the first element is: a
TreeSet Elements:
a;b;d;
```
阅读全文