在Java中搜索嵌套对象的逻辑是什么?(What is the logic for searching nested objects in Java?)

编程入门 行业动态 更新时间:2024-10-08 06:27:07
在Java中搜索嵌套对象的逻辑是什么?(What is the logic for searching nested objects in Java?)

我有一个Person对象结构如下,我想根据他的名字搜索一个Person。

public Person{ String name; List<Person> person; }

我们如何实现这个搜索方法?

将有一个根对象是Person,并且它具有与其他人的链接等。

人的名字是独一无二的。

搜索签名可能是

public Person findPerson(Person root, String name){ }

我可以把它看作是这个或这个 。

任何人都可以提出任何其他解决方案吗?

I have a object structure for Person as below and I want to search a Person on the based of his name.

public Person{ String name; List<Person> person; }

How can we implement search method for this?

There will be one root object which is Person and it has link to other persons and so on.

And the names of Persons are unique.

The search signature could be

public Person findPerson(Person root, String name){ }

I can look it as this or this.

Can anyone suggest any other solution for this?

最满意答案

你将需要递归。 遍历列表中的所有人并在该人内搜索相同的目标。 一旦你找到你的目标,返回并停止所有搜索。

这里是一些伪代码:

Person search(Person, Name) if (Person.Name == Name) return Person; for each subPerson in Person.person: Person found = subPerson.search(Person, Name); if (found != null) return found; return null;

You will need recursion. Iterate over all the persons in the List and search within that person for the same target. Once you found your target, return and stop all searching.

Here is some pseudo code:

Person search(Person, Name) if (Person.Name == Name) return Person; for each subPerson in Person.person: Person found = subPerson.search(Person, Name); if (found != null) return found; return null;

更多推荐

本文发布于:2023-04-29 07:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   逻辑   对象   Java   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!