简体   繁体   English

使用比较器而不添加类

[英]Using comparator without adding class

I am trying to sort an arraylist by string length, i know of implementing Comparator, but i was wondering if this could be done within my function, without adding any extra classes or methods? 我正在尝试按字符串长度对arraylist进行排序,我知道实现Comparator,但是我想知道是否可以在我的函数中完成此操作,而无需添加任何额外的类或方法? Ideally I want to output them shortest to longest, but that I can do! 理想情况下,我想将它们输出的最短到最长,但是我可以做到!

Here is a snippet of the method i would like to implement the comparator with. 这是我想用来实现比较器的方法的摘要。

public static void sCompare(BufferedReader r, PrintWriter w) throws IOException {

    ArrayList<String> s= new ArrayList<String>();

    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        s.add(line);
        n++;
    }
    //Collections.sort(s);  

    Iterator<String> i = s.iterator();
    while (i.hasNext()) {
        w.println(i.next());
    }
  }

Thanks in advance for any input! 预先感谢您的任何投入!

I don't see anything wrong with implementing the Comparator interface. 我看不到实现Comparator接口有什么问题。 If your only concern is doing everything in the function, you could use an anonymous implementation. 如果您唯一关心的是执行函数中的所有操作,则可以使用匿名实现。 Something along the lines of : 类似于以下内容:

    Collections.sort(s, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.length() - o2.length();
        }
    });  

(that would replace you current line //Collections.sort(s); ) (这将替换您当前的行//Collections.sort(s);

PS : you never use the value of n . PS:您永远不会使用n的值。

PPS: You may have to invert o1 and o2 depending of the order you want in the return statement. PPS:您可能必须根据return语句中想要的顺序来反转o1和o2。

Another example of implementing an interface with an anonymous class 用匿名类实现接口的另一个示例

I'm going to assume by "class" you mean "top level class", thus allowing the use of an anonymous class : 我将假设“类”的意思是“顶级类”,从而允许使用匿名类

Collections.sort(s, new Comparator<String>() {
    public int compare(String a, String b) {
        // java 1.7:
        return Integer.compare(a.length(), b.length());
        // java 1.6
        return a.length() - b.length();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM