In my Java program, I need to operate on the sublists a of ArrayList
or LinkedList
often, like removing a sublist, comparing two sublists.
For ArrayList
or LinkedList
, I didn't find any good APIs to do these. My current implementation is as below. Basically, it takes an input like:
u1234 u1236 u1236 u2def u1236 u1236 u2def
and outputs the following:
u1234 ( ( u1236 ) * u2def ) *
Core function:
ArrayList<String> toRegex(ArrayList<String> tokenArray)
{
/* check different length of continuous duplication */
for(int len=1; len<=tokenArray.size()/2; len++)
{
boolean match = false;
/* given a length, scan for duplication */
for(int i=0; i<tokenArray.size()-(2*len-1); i++)
{
ArrayList<String> first = new ArrayList<String>();
ArrayList<String> second = new ArrayList<String>();
for(int j=i; j<i+len; j++)
first.add(tokenArray.get(j));
for(int j=i+len; j<i+2*len; j++)
second.add(tokenArray.get(j));
if(isSpecial(first)) { /* skip the cases */
continue;
}
while(isIdentical(first, second))
{
match = true;
for(int j=i+len; j<i+2*len; j++)
tokenArray.remove(i+len);
if(i+2*len > tokenArray.size())
break;
second.clear();
for(int j=i+len; j<i+2*len; j++)
second.add(tokenArray.get(j));
}
if(match == true) {
tokenArray.add(i, "(");
tokenArray.add(i+1+len, ")");
tokenArray.add(i+2+len, "*");
i = i+3+len;
match = false;
}
}
}
return tokenArray;
}
Currently, the performance is not good. Could you find the bad design or inappropriate usage of data structures/APIs? What are the good common ways of operating sublists?