【问题标题】:Is it possible to check, if a function was called?是否可以检查是否调用了函数?
【发布时间】:2012-11-27 19:00:08
【问题描述】:

我有一个ArrayList 的对象,我需要使用两个属性(使用比较器)对其进行排序。我需要将排序后的输出保存到具有不同名称的文本文件中,具体取决于用于排序的属性。例如,如果列表按attribute1 排序,则文件将为attribute1.txt,如果attribute2,则文件将为attribute2.txt

我希望它如何工作(伪代码):

if(sortedByAtr1){
    FileWriter fwstream = new FileWriter(sortedByAtribute1.getName()+".txt");   
}
else(sortedByAtr2){
    FileWriter fwstream = new FileWriter(sortedByAtribute2.getName()+".txt");
}

这可能吗? 我很感激任何建议。 谢谢。

伺服

【问题讨论】:

  • 是的,这是可能的。您必须在 if 语句之外定义 FileWriter fwstream,因此您可以在 if 后面的代码中使用它。
  • 您能否为我们提供更多上下文,例如排序是如何完成的,当您使用attribute1attribute2 进行排序时,您不能只设置一个变量?就像isAttribute1 = false 表示它是attribute2 被调用。或者一个字符串..我们需要更多信息。
  • 它的行数太多了。但是@Gilbert Le Blanc 有一个很好的观点,谢谢。

标签: java file outputstream


【解决方案1】:

这是解决此要求的面向对象的方法。

对 List 及其排序属性使用包装器:

public class ListSorter<V> {

    private final List<V> values;
    private String sortingAttribute;

    public ListSorter(List<V> values) {
        this.values = values;
    }

    public void sort(AttributeComparator<V> comparator) {
        Collections.sort(values, comparator);
        sortingAttribute = comparator.getSortingAttribute();
    }

    public String getSortingAttribute() {
        return sortingAttribute;
    }
}

扩展 Comparator 接口,以便获取属性名称:

public interface AttributeComparator<T> extends Comparator<T> {
    public String getSortingAttribute();
}

像这样创建自定义属性比较器:

public class FooBarComparator implements AttributeComparator<Foo> {

    public int compare(Foo foo1, Foo foo2) {
        // skipped nullchecks for brevity
        return foo1.getBar().compare(foo2.getBar());
    }

    public String getSortingAttribute() {
        return "bar";
    }

}

用途:

List<Foo> yourList = new ArrayList<Foo>();
ListSorter<Foo> example = new ListSorter<Foo>(yourList);
AttributeComparator comparator1 = new FooBarComparator();
example.sort(comparator1);
FileWriter fwstream = new FileWriter(example.getSortingAttribute() +".txt"); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2017-12-20
    • 2020-03-12
    • 2021-06-26
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多