请参考doIt函数。
每当我将尾置存储在变量中并对其执行操作时,它也会更改我的 ss 变量的值。如何在不将其从主排序集 ss(ss) 中删除尾组的第一个元素的情况下删除它?
输入文件:
苹果
奶酪
开胃酒
种族隔离
多瑙河
猿
便宜
便宜
.app
谢亚
担
输出文件: 苹果
史:[苹果、奶酪] 删除后的SS[苹果]
史:[开胃酒,苹果] 删除后的SS[苹果]
史:[种族隔离,苹果] 删除后的SS[苹果]
史:[苹果,多瑙河] 删除后的SS[苹果]
史:[猿,苹果] 删除后的SS[苹果]
史:[苹果,便宜] 删除后的SS[苹果]
史:[苹果,便宜] 删除后的SS[苹果]
SS: [应用程序,苹果] 删除后的SS[苹果]
史:[苹果,谢] 删除后的SS[苹果]
史:[苹果,丹] 删除后的SS[苹果]
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Part4 {
/**
*
* @param r the reader to read from
* @param w the writer to write to
* @throws IOException
*/
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
SortedSet<String> ss = new TreeSet<String>();
for (String line = r.readLine(); line != null; line = r.readLine()) {
if (ss.isEmpty()) {
ss.add(line);
w.println(line);
} else {
w.println("");
ss.add(line);
w.println("ss: " + ss);
SortedSet<String> tailset = new TreeSet<>();
tailset = ss.tailSet(line);
tailset.remove(line);
w.println("ss after remove"+ss);
}
}
}
/**
* The driver. Open a BufferedReader and a PrintWriter, either from System.in
* and System.out or from filenames specified on the command line, then call
* doIt.
*
* @param args
*/
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long arrlirt = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 1e-9 * (stop - arrlirt));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}
返回tailSet()
中的更改会自动"传输"回原始SortedSet
,如SortedSet.tailSet(E)
文档中所述:
返回此集合中元素大于或等于 fromElement 的部分的视图。返回的集受此集支持,因此返回集中的更改将反映在此集中,反之亦然。
但是,您可以使用TreeSet
的"copy"构造函数创建返回的SortedSet
实例的副本,如下所示:
w.println("ss: " + ss);
SortedSet<String> tailset = new TreeSet<String>(ss.tailSet(line));
tailset.remove(line);
这样,您就有了一个单独的SortedSet
实例,您可以在其中调用remove()
而无需更改原始SortedSet
实例。