我有一个简单的代码如下:
import java.util.ArrayList;
public class BoidList extends ArrayList
{
synchronized public Boid GetBoid( int idx_ ) throws ArrayIndexOutOfBoundsException
{
if( idx_ < super.size() &&
idx_ >= 0 )
{
return (Boid) super.get(idx_);
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
synchronized public void RemoveBoid( int idx_ ) throws ArrayIndexOutOfBoundsException
{
if( idx_ < super.size() &&
idx_ >= 0 )
{
super.remove(idx_);
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
两种方法之间有很多相似之处,但它们做了两件不同的事情.有可能重构这个吗?
har*_*rto 20
这个的真正目的是BoidList什么?考虑以下:
List<Boid> boids = Collections.synchronizedList(new ArrayList<Boid>());
Run Code Online (Sandbox Code Playgroud)
这行代码或多或少等同于您尝试创建的子类:
ArrayListIndexOutOfBoundsException如果索引无效,则抛出一个Collections.synchronizedList() 确保对列表的同步访问根据您提供的源代码,我认为没有任何理由创建您自己的子类.
dfa*_*dfa 12
public class BoidList extends ArrayList<Boid> {
private void checkIndex(int idx) {
if (idx >= super.size() || idx < 0) {
throw new ArrayIndexOutOfBoundsException(String.valueOf(idx));
}
}
synchronized public Boid getBoid(int idx) {
checkIndex(idx);
return super.get(idx);
}
synchronized public void removeBoid(int idx) {
checkIndex(idx);
super.remove(idx);
}
}
Run Code Online (Sandbox Code Playgroud)
这会以多种方式修复您的代码:
编辑
您可能还想检查CopyOnWriteArrayList <Boid>
| 归档时间: |
|
| 查看次数: |
580 次 |
| 最近记录: |