bar*_*rry 0 java arrays performance arraylist
使用Java,我有一个类,它将网页检索为字节数组.然后我需要删除一些内容(如果存在).(该应用程序监视网页的变化,但需要从PHP创建的html中删除会话ID,并且意味着每次访问该页面时都会检测到更改).
一些生成的字节数组可能是1000个字节长的10.它们不是这样存储的 - 存储了16字节的MD5页面.但是,它是需要处理的原始全尺寸字节数组.
(更新 - 代码不起作用.请参阅下面的AH评论)显示我的代码的测试:
public void testSessionIDGetsRemovedFromData() throws IOException
{
byte[] forumContent = "<li class=\"icon-logout\"><a href=\"./ucp.php?mode=logout&sid=3a4043284674572e35881e022c68fcd8\" title=\"Logout [ barry ]\" accesskey=\"x\">Logout [ barry ]</a></li>".getBytes();
byte[] sidPattern = "&sid=".getBytes();
int sidIndex = ArrayCleaner.getPatternIndex(forumContent, sidPattern);
assertEquals(54, sidIndex);
// start of cleaning code
ArrayList<Byte> forumContentList = new ArrayList<Byte>();
forumContentList.addAll(forumContent);
forumContentList.removeAll(Arrays.asList(sidPattern));
byte[] forumContentCleaned = new byte[forumContentList.size()];
for (int i = 0; i < forumContentCleaned.length; i++)
{
forumContentCleaned[i] = (byte)forumContentList.get(i);
}
//end of cleaning code
sidIndex = ArrayCleaner.getPatternIndex(forumContentCleaned, sidPattern);
assertEquals(-1, sidIndex);
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但我担心清洁部分的效率.我原本希望只在数组上运行,但ArrayList有很好的内置函数来从ArrayList中删除一个集合,这正是我需要的.所以我不得不创建一个Byte的ArrayList,因为我不能拥有原始字节的ArrayList(任何人都可以告诉我为什么?),将模式转换为删除到另一个ArrayList(我想这可能是一个ArrayList一直)传递给removeAll().然后我需要创建另一个byte []并将Bytes的ArrayList的每个元素转换为一个字节并将其添加到byte [].
有没有更有效的方法来做这一切?可以使用数组执行吗?
更新 这是使用字符串的相同功能:
public void testSessionIDGetsRemovedFromDataUsingStrings() throws IOException
{
String forumContent = "<li class=\"icon-logout\"><a href=\"./ucp.php?mode=logout&sid=3a4043284674572e35881e022c68fcd8\" title=\"Logout [ barry ]\" accesskey=\"x\">Logout [ barry ]</a></li>";
String sidPattern = "&sid=";
int sidIndex = forumContent.indexOf(sidPattern);
assertEquals(54, sidIndex);
forumContent = forumContent.replaceAll(sidPattern, "");
sidIndex = forumContent.indexOf(sidPattern);
assertEquals(-1, sidIndex);
}
Run Code Online (Sandbox Code Playgroud)
这和array/arrayList方法一样有效吗?
谢谢,巴里
您可以使用List#toArray()将任何列表转换为数组.
事情是在这种特殊情况下使用更复杂一些,因为有(从没有优雅的方式来自动拆箱Byte到byte转换列表时).好的'Java泛型.这是一个很好的细节...
所以我不得不创建一个Byte的ArrayList,因为我不能拥有原始字节的ArrayList(有人可以告诉我为什么吗?)
因为,在Java中,泛型类型参数不能是原语.请参阅为什么Java Collections不能直接存储Primitives类型?
旁注:作为一种风格问题,您几乎应该始终将ArrayList类型声明为List:
List<Byte> forumContentList = new ArrayList<Byte>();
Run Code Online (Sandbox Code Playgroud)
请参阅Java - 在接口类型中声明,而不是Java中的类和类型列表与类型ArrayList.
| 归档时间: |
|
| 查看次数: |
683 次 |
| 最近记录: |