在这篇文章中,我们将看到 Java 中的 TreeSet。 Java TreeSet 具有以下属性:
让我们在示例的帮助下更深入地理解它。
1) 创建一个名为 Country.java 的类。
package com.org.arpit.java2blog; public class Country implements Comparable{ String countryName; public Country(String countryName) { super(); this.countryName = countryName; } @Override public int compareTo(Object arg0) { Country country=(Country) arg0; return (this.countryName.compareTo(country.countryName) ) ; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } }
2)创建TreeSetMain.java如下:
package com.org.arpit.java2blog; import java.util.Iterator; import java.util.TreeSet; public class TreeSetMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country("India"); Country chinaCountry=new Country("China"); Country nepalCountry=new Country("Nepal"); Country bhutanCountry=new Country("Bhutan"); Country indiaCountry2=new Country("India"); Country nepalCountry2=new Country("Nepal"); TreeSet countryTreeSet = new TreeSet(); countryTreeSet.add(indiaCountry); countryTreeSet.add(chinaCountry); countryTreeSet.add(nepalCountry); countryTreeSet.add(bhutanCountry); countryTreeSet.add(indiaCountry2); countryTreeSet.add(nepalCountry2); Iterator counIter=countryTreeSet.iterator(); // put debug point here while(counIter.hasNext()) { System.out.println(counIter.next().countryName); } } }
当你运行上面的程序时,你会得到以下结果:
Bhutan China India Nepal
如您所见,我们在 Treeset 中添加了 6 个国家对象,但我们只有 4 个!!由于 TreeSet 只能有唯一元素,indiaCountry2 和 nepalCountry2 没有添加到 TreeSet。解释:
当您将 indiaCountry2 放入 treeSet 时,它将将此对象与 indiaCountry 进行比较,如 indiaCountry2.compareTo(indiaCountry) 和 compareTo 方法将返回 0。这两个对象将被视为相等。由于不能在 TreeSet 中添加重复元素,因此不会将 indiaCountry2 添加到上述 TreeSet 中。
现在将调试点放在第 27 行,然后右键单击 project->debug as-> java应用程序。程序将在第 27 行停止执行,然后右键单击 countryTreeSet 然后选择 watch。您将能够看到如下结构。
猜测以下程序的输出:
package com.org.arpit.java2blog; import java.util.Iterator; import java.util.TreeSet; public class Employee implements Comparable { public String name; public int compareTo(Object o) { return 0; } public static void main(String args []) { Employee employeeOne = new Employee(); Employee employeeTwo = new Employee(); employeeOne.name= "John"; employeeTwo.name= "Martin"; TreeSet employeeSet = new TreeSet(); employeeSet.add(employeeOne); employeeSet.add(employeeTwo); Iterator empIt=employeeSet.iterator(); while(empIt.hasNext()) { System.out.println(empIt.next().name); } } }
上述程序将输出什么: A. Martin B. John C. John Martin D. 编译失败。 E. 代码运行没有输出。 F. 运行时抛出异常。
这里正确答案是B。
如您所见,我们在 Employee 类中重写了 compareTo 方法并始终返回 0。 将执行以下步骤:
原文链接:https://codingdict.com/