我们知道,直接传入字符串数组是不可行的,这种模式就写“死”了,前面讲到面向接口编程,需要用到什么样子的实现类就new一个实现类即可。
二、具体代码package com.wsy;
public interface MyFilterAccessor {
public String[] values();
public String getField();
}
class MyFilterImpl implements MyFilterAccessor {
@Override
public String[] values() {
return new String[]{"1", "3", "5"};
}
@Override
public String getField() {
return "id";
}
}
在上一节的MyFilter类中,添加MyFilterAccessor属性,在MyFilter构造函数中对MyFilterAccessor对象初始化。原来的for循环优化成下面的样子。用myFilterAccessor.values()替代了之前写死的字符串数组,用myFilterAccessor.getField()替代了之前写死的field。
for (String deleteId : myFilterAccessor.values()) {
// 获取TermDocs
TermDocs termDocs = indexReader.termDocs(new Term(myFilterAccessor.getField(), deleteId));
// 将查询出来的对象的位置存在docs中,将查询出现的频率存放在freqs中,返回查询出来的条数
int count = termDocs.read(docs, freqs);
// count == 1表明这个是主键
System.out.println("count=" + count + "\tdocs=" + docs[0] + "\tfreqs=" + freqs[0]);
if (count == 1) {
// 将这个位置的元素删除
openBitSet.clear(docs[0]);
}
}
同时又写了两个方法,一个是用来set的,一个是用来clear的。
private void set(IndexReader indexReader, OpenBitSet openBitSet) {
try {
int[] docs = new int[1];
int[] freqs = new int[1];
for (String deleteId : myFilterAccessor.values()) {
// 获取TermDocs
TermDocs termDocs = indexReader.termDocs(new Term(myFilterAccessor.getField(), deleteId));
// 将查询出来的对象的位置存在docs中,将查询出现的频率存放在freqs中,返回查询出来的条数
int count = termDocs.read(docs, freqs);
// count == 1表明这个是主键
System.out.println("count=" + count + "\tdocs=" + docs[0] + "\tfreqs=" + freqs[0]);
if (count == 1) {
openBitSet.set(docs[0]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void clear(IndexReader indexReader, OpenBitSet openBitSet) {
try {
openBitSet.set(0, indexReader.maxDoc() - 1);
// 获取需要被过滤掉的docId,将它的值清空
int[] docs = new int[1];
int[] freqs = new int[1];
for (String deleteId : myFilterAccessor.values()) {
// 获取TermDocs
TermDocs termDocs = indexReader.termDocs(new Term(myFilterAccessor.getField(), deleteId));
// 将查询出来的对象的位置存在docs中,将查询出现的频率存放在freqs中,返回查询出来的条数
int count = termDocs.read(docs, freqs);
// count == 1表明这个是主键
System.out.println("count=" + count + "\tdocs=" + docs[0] + "\tfreqs=" + freqs[0]);
if (count == 1) {
openBitSet.clear(docs[0]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}