2016-07-12 1 views
0

설명하기가 조금 어렵습니다. 이 예제 코드 :상위 - 하위 관계를 기반으로 항목 내에 중첩 된 (계층 구조) 모든 항목의 목록을 가져 오는 방법은 무엇입니까?

public class SomeClass 
{ 
    private String id; 
    private String parent; 

    public SomeClass(String id, String parent) 
    { 
     this.id = id; 
     this.parent = parent; 
    } 

    public String getParent() 
    { 
     return parent; 
    } 
} 

List<SomeClass> someList = new ArrayList(); 
someList.add(new SomeClass("Test1", "none")); 
someList.add(new SomeClass("Test2", "none")); 
someList.add(new SomeClass("Test1Mem1", "Test1")); 
someList.add(new SomeClass("Test2Mem1", "Test2")); 
someList.add(new SomeClass("Test1Mem1Obj1", "Test1Mem1")); 

나는 그것이 "부모"필드 계층의에서 개체를 포함하는 모든 개체를 가져옵니다 기능을 만들려고합니다. 예를 들어 "Test1Mem1Obj1"을 찾으면 "{Test1Mem1, Test1}"값을 제공해야하며 "Test2Mem1"을 찾으면 "{Test2}"값을 제공해야합니다. 기본적으로 부모의 부모의 부모를 가져 오는 등의 작업을 수행합니다. 언어 장벽으로 인해이 설명에 불편을 끼쳐 드려 죄송합니다. 누군가가 나를 도와 줄 수 있기를 바랍니다. 고맙습니다!

일시적인 더러운 솔루션이 있는데 왜 좋지 않은지 알 수 있습니다. 당신이 할 수있는 경우

if(someObj.getParent() != null) 
{ 
    result.add(someObj.getParent()); 

    if(someObj.getParent().getParent() != null) 
    { 
     result.add(someObj.getParent().getParent()); 

     if(someObj.getParent().getParent().getParent() != null) 
     { 
      result.add(someObj.getParent().getParent().getParent()); 
     } 
    } 
} 
+0

List가 사용되는 것은 필수입니까? 트리 구조가 여기서 더 잘 작동 할 수 있다고 생각합니다. –

+0

또한 나는 MySQL 데이터베이스에서 목록을로드한다는 것을 언급해야한다. 그래서 그것은 어떤 순서도없고 구현에 대한 제한이 없으며 Tree 구조를 사용할 수 없습니다. – TheAwesomeGem

+0

고유 한 ID가 있습니까? 대신지도를 사용할 수 있습니까? – Crummy

답변

1

하는 getParent()SomeClass 대신 String (A)의 반환 꽤 쉽게 :

public boolean isDescendantOf(String parentName) { // part of SomeClass 
    SomeClass parent = this.parent; 
    while (!parent.id.equals("none")) { // or null check 
     if (parent.id.equals(parentName)) { 
      return true; // found a parent named parentName 
     } 
    } 
    return false; // eventually reached a parentless parent and never found one matching parentName 
} 

은 어쩌면 비록 수 없습니다. 당신이 대신 맵에 물건을 넣어과 같이 할 수있는 경우 : 모든 부모의 목록을 채우려면

public boolean isDescendentOf(SomeClass child, String parentName) { 
    SomeClass parent = map.get(child.parent); 
    if (parent == null) { 
     throw new RuntimeException("Warning: parent doesn't exist!"); 
    } 
    if (parent.id.equals(parentName)) { 
     return true; 
    } else { 
     return isDescendentOf(parent, parentName); 
    } 
} 

: 다음

Map<String, SomeClass> map = new HashMap<>(); // map from parent name to SomeClass 
map.put("Test1", new SomeClass("Test1", "none")); 
map.put("Test2", new SomeClass("Test2", "none")); 
map.put("Test1Mem1", new SomeClass("Test1Mem1", "Test1")); 
map.put("Test2Mem1", new SomeClass("Test2Mem1", "Test2")); 
map.put("Test1Mem1Obj1", new SomeClass("Test1Mem1Obj1", "Test1Mem1")); 

당신은 재귀를 같은 위에 루프를 사용하여 수 주어진 요소에 대해 다음과 같은 함수를 호출하십시오.

public static void PopulateParents(List<String> parents, Map<String, ClassTest> nodes, ClassTest child) { 
    if (child.parent.equals("none")) { 
     return; 
    } 
    ClassTest parent = nodes.get(child.parent); 
    if (parent == null) { 
     throw new RuntimeException("No parent exists called " + child.parent); 
    } 
    parents.add(parent.id); 
    PopulateParents(parents, nodes, parent); 
} 
+0

답장을 보내 주셔서 감사합니다. 나는 당신이 당신을 게시하자마자 해결책을 찾아 냈습니다. 이제 내가 물을 수 있다면 여기에 효율적으로 일하고 있다면 : http : //hastebin.com/faqazagoze.avrasm – TheAwesomeGem

+0

SomeTest의 부모, 조부모 등을 모두 인쇄하려고합니까? – Crummy

+0

예. 내가 stackoverflow 얻을 수 있다고 생각합니까? – TheAwesomeGem

관련 문제