【问题标题】:Nested ArrayList lookup嵌套 ArrayList 查找
【发布时间】:2019-01-21 23:06:47
【问题描述】:

所以我需要返回某个行程的出发点,这里有几个例子:

旅行 := [ [A,B], [B,C], [C,D] ] 本例中的行程从“A”开始。

行程 := [ [D,E], [F,D], [E,X] ] 本例中的行程从“F”开始。

为此,我做了 2 个循环来比较 A 与 C 和 D,如果 A 在任何地方都不存在,那么它就是出发点。

是否可以这样做(保持 2 个循环)并更改条件中的某些内容以仅获取出发城市?

ArrayList<ArrayList> tripsList = new ArrayList<ArrayList>();
ArrayList<String> trip1 = new ArrayList<String>();
ArrayList<String> trip2 = new ArrayList<String>();
ArrayList<String> trip3 = new ArrayList<String>();

tripsList.add(trip1);
tripsList.add(trip2);
tripsList.add(trip3);

trip1.add("Hamburg");
trip1.add("Berlin");

trip2.add("Mainz");
trip2.add("Frankfurt");    

trip3.add("Frankfurt");
trip3.add("Hamburg");

System.out.println(tripsList);

for (int i=0; i < 3 ; i++)
{
  for (int j=0; j < 3 ; j++)
  {
    if (tripsList.get(i).get(0)!=tripsList.get(j).get(1)) 

      System.out.println("your place is "+tripsList.get(i).get(0));
  } 
}`

输出如下:

[[Hamburg, Berlin], [Mainz, Frankfurt], [Frankfurt, Hamburg]] your place is Hamburg your place is Hamburg your place is Mainz your place is Mainz your place is Mainz your place is Frankfurt your place is Frankfurt

【问题讨论】:

  • 忘了说是随机的,不一定是开头,所以需要一个函数来查找。
  • 听起来有点像拓扑排序。

标签: java arrays arraylist nested-loops


【解决方案1】:

使用标志等待检查所有结果:

Boolean anyMatches = False;
For (int i= 0; i < 3 ; i++) 
{
    anyMatches = false;
    For (int j= 0; j < 3 ; j++) 
    {
        If (tripsList.get(i).get(0) == tripsList.get(j).get(1))
        {
            anyMatches = true;
        }
    }
    If (anyMatches == False)  
    {
        SystemThen.out.println("Your Departure City is "+tripsList.Get(i).Get(0));
    }
}

【讨论】:

  • 非常感谢,这正是我想做的!这是最简单、最干净的方法吗?
  • 这不是最干净的方式,因为即使我们知道我们没有查看出发城市,它也会继续通过内循环,即使在确定出发城市之后它也会继续通过主循环。
【解决方案2】:

一旦找到出发方法就停止搜索,希望对你有帮助

ArrayList<ArrayList<String>> tripsList = new ArrayList<>();
ArrayList<String> trip1 = new ArrayList<String>();
ArrayList<String> trip2 = new ArrayList<String>();
ArrayList<String> trip3 = new ArrayList<String>();

tripsList.add(trip1);
tripsList.add(trip2);
tripsList.add(trip3);

trip1.add("D");
trip1.add("E");

trip2.add("F");
trip2.add("D");

trip3.add("E");
trip3.add("X");

System.out.println(tripsList);

String departure = "";
for (int i = 0; i < tripsList.size(); i++) {
    if (!departure.equals("")) {
        break;
    }
    departure = tripsList.get(i).get(0);
    for (int j = 0; j < tripsList.size(); j++) {
        if ( j == i) {
            continue;
        }
        if (departure.equals(tripsList.get(j).get(1))) {
            departure = "";
            break;
         }
    }
}
System.out.println(departure);

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多