神奇的模板--在树结构下一个节点的子节点可以是不同的类型

public class Node4XML<T> {

//数据 //各种类型
T data;

//子节点
Node4XMLList node4XMLList;

public <X> void addsubNode(Node4XML<X> subNode) {
node4XMLList.addsubNode(subNode);
}

public Node4XML<?> getSubNode(int index){
return node4XMLList.get(index);
}

public Node4XML(T data, Node4XMLList node4xmlList) {
super();
this.data = data;
node4XMLList = node4xmlList;
}

public T getData() {
return data;
}

}

import java.util.ArrayList;
import java.util.List;

public class Node4XMLList {

//子节点
private List < Node4XML<?> > subNodes = new ArrayList< Node4XML<?> >();

public <X> void addsubNode(Node4XML<X> subNode) {
subNodes.add(subNode);
return;
}

public Node4XML<?> get(int index){
return subNodes.get(index);
}


public <X> X fun(X x){
return x;
}

}

public class TypeA {

int a;
String strA;

public void print(){
System.out.println("TypeA a: " + a);
System.out.println("TypeA strA: " + strA);
}

public TypeA(int a, String strA) {
super();
this.a = a;
this.strA = strA;
}

}


public class TypeB {

int b;
String strB;

public void print(){
System.out.println("TypeB b: " + b);
System.out.println("TypeB strB: " + strB);
}

public TypeB(int b, String strB) {
super();
this.b = b;
this.strB = strB;
}

}


public class TypeC {

int c;
String strC;

public void print(){
System.out.println("TypeC c: " + c);
System.out.println("TypeC strC: " + strC);
}

public TypeC(int c, String strC) {
super();
this.c = c;
this.strC = strC;
}
}


public class MainTest {

public static void charTest(){
int testTurn = 1;
char x = (char) (testTurn + 64);
System.out.println(x);

String xy = "xx/" + x;
System.out.println(xy);
}

//模板测试
public static void typeTest(){

//三级目录
Node4XML<TypeA> root = new Node4XML<TypeA>(new TypeA(1, "a"), new Node4XMLList());
//root.setData(new TypeA(1, "a"));

Node4XML<TypeB> nodeb = new Node4XML<TypeB>(new TypeB(2, "b"), new Node4XMLList());
root.addsubNode(nodeb);

Node4XML<TypeC> nodec = new Node4XML<TypeC>(new TypeC(3, "c"), new Node4XMLList());
nodeb.addsubNode(nodec);

TypeA xa = root.getData();
xa.print();

Node4XML<?> secnode = root.getSubNode(0);
TypeB xb = (TypeB) secnode.getData();
xb.print();

Node4XML<?> thirdnode = secnode.getSubNode(0);
TypeC xc = (TypeC) thirdnode.getData();
xc.print();

}

public static void main(String[] args) throws Exception {

MainTest.typeTest(); //递归模板
System.out.println();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值