【问题标题】:Java sorting with collections plus manual sorting使用集合和手动排序进行 Java 排序
【发布时间】:2013-04-30 16:35:20
【问题描述】:

我正在编写一个使用哈希表计算各种价格的控制台应用程序。它使用名为 Priceprint 的类写入价格。我在程序的其余部分使用哈希表,因为顺序并不是特别重要,但它会在创建列表作为输出之前对键进行排序。它通过将键放入向量中,使用 Collections.sort() 对向量进行排序并手动将第一个和第二个键与键交换和特殊的条目交换,从而将它们按顺序排列。然后它使用枚举从向量中获取所有内容,并调用另一个函数将每个条目写入屏幕。

public void out(Hashtable<String, Double> b, Hashtable<String, Double> d) {
            Vector<String> v;
            Enumeration<String> k;
            String te1, te2, e;
            int ex, sp;

            v = new Vector<String>(d.keySet());
            Collections.sort(v);

            te1 = new String(v.get(0));
            ex = v.indexOf("exchange");
            v.set(ex, te1); v.set(0, "exchange");

            te2 = new String(v.get(1));
            ex = v.indexOf("special");
            v.set(ex, te2); v.set(1, "special");

            if (msgflag == true)
                    System.out.println("Listing Bitcoin and dollar prices.");
            else {
                    System.out.println("Listing Bitcoin and dollar prices, "
                                       + message + ".");
                    msgflag = true;
            }

            k = v.elements();
            while (k.hasMoreElements()) {
                    e = new String(k.nextElement());
                    out(e, d.get(e), b.get(e));
            }
    }

现在的问题是我仅仅因为缺乏想法而遇到的问题是交换条目并按其键的字母顺序对列表进行排序。所以当我运行程序交换时,特别是在顶部,但列表的其余部分不再按顺序排列。我可能不得不放弃通过代码输出列表的基本设计,其中包含键价格和特殊项的代码输出到顶部,但与列表的所有其他方面都有顺序。很遗憾,因为它几乎都可能需要完成,而且我真的很喜欢这个设计。

这是完整的代码,忽略我在一个显然应该使用静态方法但忽略了的类上使用构造函数的事实:http://pastebin.com/CdwhcV2L

这是使用 Printprice 创建价格列表以测试程序的另一部分以及 Printprice 列表的代码:http://pastebin.com/E2Fq13zF

输出:

john@fekete:~/devel/java/pricecalc$ java backend.test.Test 
I test CalcPrice, but I also test Printprice(Hashtable, Hashtable, String).
Listing Bitcoin and dollar prices, for unit test, check with calculator.
Exchange rate is $127.23 (USDBTC).
Special is 20.0%.
privacy:    $2.0    0.0126BTC, for unit test, check with calculator.
quotaband:  $1.5    0.0094BTC, for unit test, check with calculator.
quotahdd:   $5.0    0.0314BTC, for unit test, check with calculator.
shells:     $5.0    0.0314BTC, for unit test, check with calculator.
hosting:    $10.0   0.0629BTC, for unit test, check with calculator.

【问题讨论】:

    标签: java vector hashtable enumeration


    【解决方案1】:

    问题似乎是您将第一个和第二个元素放回向量中“exchange”和“special”来自的位置,而不是从向量中删除“exchange”和“special”并插入它们位于向量的顶部。

    使用 LinkedList 而不是 Vector,正确执行此操作会更有效。进行所需的操作,假设vList

    v.add(0, v.remove(v.indexOf("special")));  
    v.add(0, v.remove(v.indexOf("exchange")));
    

    这应该把“exchange”放在第一位,“special”放在第二位,然后列表的其余部分将保持排序。

    【讨论】:

    • 谢谢!这使它变得既好又简单。
    最近更新 更多