2015-10-25 48 views
0

假設我有TASK數組列表{A,B,C,D,E,F}和Dependencies數組列表,指示每個對應的TASK {-,-,A,AB,CD,E}反向檢查ArrayList中的所有依賴關係java

我沒有問題找到Java程序中的前向依賴項,但是如果我想將其反向並存儲到新陣列後向列表中,如{CD,D,E,E,F,-}

轉發:

enter image description here

回答

0

這是一個有點不清楚我怎麼你的任務是確定,但假設一個任務是這樣的一類:

class Task { 

    private final String name; 

    public Task(String name) { 
     this.name = name; 
    } 

    public String getName() { 
     return name; 
    } 

    @Override 
    public String toString() { 
     return name; 
    } 
} 

然後,你可以定義你的輸入數組列表像這樣(假設您已經靜態導入asList()和emptyList()方法):

final Task a = new Task("A"); 
    final Task b = new Task("B"); 
    final Task c = new Task("C"); 
    final Task d = new Task("D"); 
    final Task e = new Task("E"); 
    final Task f = new Task("F"); 

    List<Task> tasks = asList(a, b, c, d, e, f); 

    List<List<Task>> dependencies = asList(
     emptyList(), 
     emptyList(), 
     asList(a), 
     asList(a, b), 
     asList(c, d), 
     asList(e) 
    ); 

計算前向引用可以用很多方法完成。這裏有一個例子:

public List<List<Task>> forwardDependencies(
     List<Task> tasks, 
     List<List<Task>> dependencies 
    ) { 
    List<List<Task>> forwardDependencies = new ArrayList<>(); 

    for (Task task : tasks) { 
     List<Task> forwardDependency = new ArrayList(); 
     for (int i = 0; i < dependencies.size(); i++) { 
      List<Task> dependency = dependencies.get(i); 
      if (dependency.contains(task)) { 
       forwardDependency.add(tasks.get(i)); 
      } 
     } 
     forwardDependencies.add(forwardDependency); 
    } 
    return forwardDependencies; 
} 

調用

 System.out.println(forwardDependencies(tasks, dependencies)); 

會產生

 [[C, D], [D], [E], [E], [F], []] 
+0

你感謝您的幫助。 –