如何使用该TreeSet
的副本并将副本打印出来?
我创建了一个方法,允许我从文本文件中填充一个没有重复项的数组,现在我需要将这些重复项写入另一个文件中。我怎么做呢?
// method that gets that reads the file and puts it in to an array
public static void readFromfile() throws IOException {
// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
// create a new array set Integer list
Set<Integer> set = new TreeSet<Integer>();
// add the numbers to the list
while (inputFile.hasNextInt()) {
set.add(inputFile.nextInt());
}
// transform the Set list in to an array
Integer[] numbersInteger = set.toArray(new Integer[set.size()]);
// loop that print out the array
for (int i = 0; i < numbersInteger.length; i++) {
System.out.println(numbersInteger[i]);
}
// close the input stream
inputFile.close();
}
可以在添加到TreeSet
或任何Set
时收集副本:
List<Integer> dups = new ArrayList<Integer>();
Set<Integer> noDups= new TreeSet<Integer>();
int i;
while (inputFile.hasNextInt()) {
{
if(!noDups.add(i=inputFile.nextInt()))
dups.add(i);
}
List<Integer> duplicates = new ArrayList<Integer>();
Set<Integer> set = new TreeSet<Integer>();
// add the numbers to the list
while (inputFile.hasNextInt()) {
Integer it = inputFile.nextInt();
if (set.contains(it)) {
duplicates.add(it); // adding duplicates which is already present in Set
} else {
set.add(it); // if not present in set add to Set
}
}
// loop ArrayList print duplicates values