首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中比较两个列表,并根据每个组合打印结果?

如何在Java中比较两个列表,并根据每个组合打印结果?
EN

Stack Overflow用户
提问于 2011-07-04 01:08:52
回答 2查看 240关注 0票数 1

我想根据价格矩阵计算每个车站之间的票价:

代码语言:javascript
复制
        a  b c 

  a     0  2 3
  b     4  0 1
  c     7  2 0

示例:基于上述价格矩阵中的值的from a to b print 2from c to a print 7

这里,我想打印基于两个车站列表的火车票票价:"from:“列表和" to :”列表。我想在比较后打印票价。每种组合都有固定的票价。例如a站到b站,票价是10美元。任何一个站到其他站都有固定的票价。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-07-04 02:06:20

我将创建一个类,它负责存储票价。

代码语言:javascript
复制
public class FareStorage {
    Map<TownCombination, Double> fares;

    //...

    public double getFare(String townA, String townB) {
        return fares.get(new TownCombination(townA, townB));
    }

    public void addFare(String townA, String townB, double fare) {
        fares.put(new TownCombination(townA, townB));
    }

    class TownCombination {
        String town1;
        String town2;

        //If a fare from A to B is equals the fare from B to A, 
        //then the A-B and the B-A combinations should be equal. 
        //Override hashCode and equals the way you want.  
    }
}

它还不完整,但我希望您能理解。下面是你使用它的方法:

代码语言:javascript
复制
        FareStorage storage = new FareStorage();
        storage.addFare("A", "B", 10.2);

        //....
        double fare = storage.get("A", "B");
票数 1
EN

Stack Overflow用户

发布于 2011-07-04 13:26:05

您也可以使用guava's Table

示例:

代码语言:javascript
复制
Table<Integer, String, String> table = HashBasedTable.create();
table.put(1, "a", "1a");
table.put(1, "b", "1b");
table.put(2, "a", "2a");
table.put(2, "b", "2b");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6564271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档