欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

某公司的面试题--递归拿到所有子类的id

程序员文章站 2022-07-10 16:17:33
...
package com;

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

public class Test1 {
	List list2 = new ArrayList();
         //构造数据库list
	public List<Student> getStudent(){
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("2","1"));
		list.add(new Student("3","2"));
		list.add(new Student("4","3"));
		list.add(new Student("5","3"));
		return list;
	}
         //循环拿到所有的子类id
	public List getAll(String i,List<Student> list){

		Iterator iter = list.iterator();
		while(iter.hasNext()){
			Student student = (Student)iter.next();
			if(i.equals(student.getParentid())){
				list2.add(student.getId());
				getAll(student.getId(),list);
			}
		}
		return list2;
	}
         //测试
	public static void main(String[] args) {
		List list = new Test1().getAll("1", new Test1().getStudent());
		Iterator iter = list.iterator();
		while(iter.hasNext()){
			System.out.println((iter.next()));
		}
	}
}
     class Student {
	private String id;
	private String parentid;

	public Student() {
	}

	public Student(String id, String parentid) {
		this.id = id;
		this.parentid = parentid;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getParentid() {
		return parentid;
	}

	public void setParentid(String parentid) {
		this.parentid = parentid;
	}
}