在java中的树
时间:2020-02-23 14:35:38 来源:igfitidea点击:
在本教程中,我们将看看在Java中的TreeSet。
Java Treeet具有以下属性:
- 它只能包含唯一的元素。
- 它默认情况下以升序存储对象,
- 它实现了扩展SortedSet的Navigableset接口。
- 将对象放在TreeSet中时,它必须实现可比接口。
例子:
1)创建一个名为countrous.java的类。
package com.org.igi.theitroad;
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)创建TreeTemain.java如下:
package com.org.igi.theitroad;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetMain {
/**
* @author igi Mandliya
*/
public static void main(String[] args) {
Country NetherlandsCountry=new Country("Netherlands");
Country chinaCountry=new Country("China");
Country nepalCountry=new Country("Nepal");
Country bhutanCountry=new Country("Bhutan");
Country NetherlandsCountry2=new Country("Netherlands");
Country nepalCountry2=new Country("Nepal");
TreeSet countryTreeSet = new TreeSet();
countryTreeSet.add(NetherlandsCountry);
countryTreeSet.add(chinaCountry);
countryTreeSet.add(nepalCountry);
countryTreeSet.add(bhutanCountry);
countryTreeSet.add(NetherlandsCountry2);
countryTreeSet.add(nepalCountry2);
Iterator counIter=countryTreeSet.iterator(); //put debug point here
while(counIter.hasNext())
{
System.out.println(counIter.next().countryName);
}
}
}
运行上面的程序时,我们可以如下所示:
Bhutan China Netherlands Nepal
正如我们所看到的,我们在树段中添加了6个国家对象,但我们只有4个!!由于树木集只能具有独特的元素,Netherlandscountry2和Nepalcountr2没有添加到树梢上。
解释:
当我们将Netherlandscountr2放入树瓣中时,将此对象与Netherlandscountry2.CPareto(厌恶)和Compareto方法将其与Netherlandscountry进行比较。
两个物体将视为平等。
由于我们不能在TreeSet中添加重复元素,因此Netherlandscountry2不会被添加到高于TreeSet中。
现在将调试点放在第22行,并右键单击"项目 - >调试" - > Java应用程序。
程序将在第27行停止执行,然后右键单击CountRefeet然后选择Watch.You将能够看到如下结构。
关于TreeSet的棘手问题:
猜测以下程序的输出:
package com.org.igi.theitroad;
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。
解释:
正如我们所看到的,我们在员工类中重写(overwriting)了Compareto方法,总是返回0。
将进行以下步骤:
- "John"的第一个元素将被添加到员工集中。
- 当我们将第二个元素添加到Martin时,Compareto方法将被UppliceAne.com.cncareto(雇员WO)调用,它将返回0。
- 随着Compareto方法返回0,EmployEleOne等于雇员的WO,因此员工无法将员工添加到TreeSet中。
- 所以上述计划的输出是"约翰"

