change the code method into TreeSet .
时间: 2024-05-04 07:20:41 浏览: 55
Class003_TreeSet.java
Sure, here's an example of how to change a Java code that uses a HashSet to use a TreeSet instead:
```
import java.util.*;
public class Example {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add some elements
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
// Print the HashSet
System.out.println("HashSet: " + hashSet);
// Create a TreeSet
Set<String> treeSet = new TreeSet<>();
// Add the elements from the HashSet to the TreeSet
treeSet.addAll(hashSet);
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
}
}
```
In this example, we first create a HashSet and add some elements to it. Then, we create a TreeSet and add the elements from the HashSet to the TreeSet using the `addAll` method. Finally, we print out both the HashSet and TreeSet to compare them.
Note that the elements in the TreeSet will be sorted in ascending order, whereas the elements in the HashSet are not guaranteed to be in any particular order.
阅读全文