[英]I am trying to create a circular LinkedList Please tell me if its a correct way to do it
i have implemented logic like if i am giving a index that is not yet there then it will change the index to the reminder (Same like rotated i guess ). 我已经实现了逻辑,例如如果我给出的索引还不存在,它将改变索引的提示(就像旋转,我猜)。
import java.util.LinkedList;
public class MycircularlinkedList extends LinkedList {
private static int count = 0;
public Object get(int i) {
System.out.println("count==" + count);
if (i > count) {
i = i % count;
return super.get(i);
} else {
return super.get(i);
}
}
public boolean add(Object o) {
super.add(o);
count++;
return true;
}
public void add(int i, Object o) {
if (i > count)
i = i % count;
super.add(i, o);
count++;
}
}
A couple of points I can see: 我可以看到几点:
count
is static, this means you're only ever going to have one number here. count
是静态的,这意味着您在这里只会有一个数字。 Probably not what you want count
is redundant, use Collection#size()
count
是多余的,请使用Collection#size()
%
) is that it works for all numbers, you don't need to have the conditional. %
)的伟大之处在于它适用于所有数字,您不需要有条件的。 2 % 12 == 14 % 12 == -10 % 12
count
property, you can get rid of your overridden #add(Object o)
logic and just do return super.add(o);
count
属性,则可以摆脱被覆盖的#add(Object o)
逻辑,而只是return super.add(o);
我发现您的代码存在一些问题:如果count == 0并且如果我使用方法add(7,obj),则7%0将引发ArithmeticException.count应该声明为private,因为您可能有两个类实例。另外,您还需要检查poll \\ offerLast方法是否满足您的需求,因为您不能限制任何客户端代码来避免使用它们。最后,需要重写clone \\ readObject \\ writeObject才能包含count变量。
You're close. 你近了
(1) The term " circular linked list " is well-known to mean a list where the tail links back to the head (and vice versa if it's a doubly-linked list). (1)术语“ 循环链表 ”是众所周知的,是指尾巴链接回头的列表(反之亦然,如果它是双链表)。 Yours is more like a "circular buffer" stored in a linked list.
您的档案更像是储存在链表中的“圆形缓冲区”。 We could call it
LinkedListCircularBuffer
or something. 我们可以称其为
LinkedListCircularBuffer
东西。
(2) The class should be parameterized by the element type, thus (2)该类应通过元素类型进行参数化,因此
public class LinkedListCircularBuffer<E> extends LinkedList<E> {
@Override
public E get(int i) {
return super.get(i % size()); // simpler and faster without an "if"
}
}
(3) You can call size()
instead of all the code to maintain another count
. (3)您可以调用
size()
而不是所有代码来维护另一个count
。
(4) Your add(int i, Object o)
method doesn't support the case where i == size()
, but you can fix that by not overriding add()
at all. (4)您的
add(int i, Object o)
方法不支持i == size()
,但是您可以通过完全不覆盖add()
来解决此问题。
(5) Overridden methods need the @Override
annotation. (5)重写的方法需要
@Override
注释。
(6) It's good style to always put braces around each "then" and "else" clause. (6) 始终在每个“ then”和“ else”子句周围使用花括号是一种很好的样式。 Code like
像这样的代码
if (i > count)
i = i % count;
is fragile, eg adding a println()
statement into that "then" clause will break it. 是脆弱的,例如,在“ then”子句中添加
println()
语句将破坏它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.