gpt4 book ai didi

java - 是否可以检查函数是否被调用?

转载 作者:行者123 更新时间:2023-12-01 15:01:24 25 4
gpt4 key购买 nike

我有一个对象的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");
}

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

伺服

最佳答案

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

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

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;
}
}

扩展比较器接口(interface),以便您可以获得属性名称:

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");

关于java - 是否可以检查函数是否被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com