Gen*_*zer 9 java arrays refactoring primitive-types
我有用于处理原始数组输入的类:char []的CharArrayExtractor,byte []的ByteArrayExtractor,int []的IntegerArrayExtractor,...
public void CharArrayExtractor {
public List<Record> extract(char[] source) {
List<Record> records = new ArrayList<Record>();
int recordStartFlagPos = -1;
int recordEndFlagPos = -1;
for (int i = 0; i < source.length; i++) {
if (source[i] == RECORD_START_FLAG) {
recordStartFlagPos = i;
} else if (source[i] == RECORD_END_FLAG) {
recordEndFlagPos = i;
}
if (recordStartFlagPos != -1 && recordEndFlagPos != -1) {
Record newRecord = makeRecord(source, recordStartFlagPos,
recordEndFlagPos);
records.add(newRecord);
recordStartFlagPos = -1;
recordEngFlagPos = -1;
}
}
}
}
public void ByteArrayExtractor {
public List<Record> extract(byte[] source) {
// filter and extract data from the array.
}
}
public void IntegerArrayExtractor {
public List<Record> extract(int[] source) {
// filter and extract data from the array.
}
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是提取数据的算法是相同的,只有输入的类型是不同的.每次算法更改时,我都必须更改所有提取器类.
有没有办法让提取器类更"泛型"?
最好的祝福.
编辑:到目前为止,似乎每个建议都是使用自动装箱来存档通用.但是阵列的元素数量通常很大,所以我避免使用自动装箱.
我添加了更具体的数据实现方式.希望它能澄清一些事情.
新理念
或者一种不同的方法是包装原始数组并使用您用于算法的方法覆盖它们。
public PrimitiveArrayWrapper {
private byte[] byteArray = null;
private int[] intArray = null;
...
public PrimitiveArrayWrapper(byte[] byteArray) {
this.byteArray = byteArray;
}
// other constructors
public String extractFoo1(String pattern) {
if(byteArray != null) {
// do action on byteArray
} else if(....)
...
}
}
public class AlgorithmExtractor {
public List<Record> do(PrimitiveArrayWrapper wrapper) {
String s= wrapper.extractFoo1("abcd");
...
}
}
Run Code Online (Sandbox Code Playgroud)
这主要取决于您是否有很多需要调用的方法。但至少您不能在如何访问原始数组的方式上更多地编辑算法。此外,您还可以在包装器内使用不同的对象。
旧观念
要么使用泛型,要么我还考虑使用三种方法将原始类型转换为值类型。
public void Extractor {
public List<Record> extract(byte[] data) {
InternalExtractor<Byte> ie = new InternalExtractor<Byte>();
return ie.internalExtract(ArrayUtils.toObject(data));
}
public List<Record> extract(int[] data) {
...
}
}
public void InternalExtractor<T> {
private List<Record> internalExtract(T[] data) {
// do the extraction
}
}
Run Code Online (Sandbox Code Playgroud)
ArrayUtils 是来自 Apache 的 commons lang 的辅助类。