LinkedList 是另一种实现形式的数组
public
class
LinkedList
extends
AbstractSequentialList
implements
List, Deque, Cloneable, Serializable
{
transient
int
size
= 0;
transient
Node
first
;
transient
Node
last
;
private
static
final
long
serialVersionUID
= 876323262645176354L;
其是不靠连续空间保存的,而是靠上下结节关系保存的数组,只能靠前一个找到后一个或后一个找到前一个。所以数据查找会比较费时,但增删却很方便
public
LinkedList
() {}
public
LinkedList(Collection
extends
E>
paramCollection
)
{
this
();
addAll(
paramCollection
);
}
老样子,构造方法一个是不带参的一个是带参的。
添加数据方法
public
void
addFirst
(E
paramE
)
{
linkFirst(
paramE
);
}
public
void
addLast(E
paramE
)
{
linkLast(
paramE
);
}
public
boolean
add
(E
paramE
)
{
linkLast(
paramE
);
return
true
;
}
支持在链表前或链表后添加数据,该数组是实现的是双向的链表。不指明默认添加在末尾。
public
boolean
addAll
(Collection
extends
E>
paramCollection
)
{
return
addAll(
this
.
size
,
paramCollection
);
}
public
boolean
addAll(
int
paramInt
, Collection
extends
E>
paramCollection
)
{
checkPositionIndex(
paramInt
);
Object[]
arrayOfObject1
=
paramCollection
.toArray();
int
i
=
arrayOfObject1
.
length
;
if
(
i
== 0) {
return
false
;
}
Node
localNode1
;
Object
localObject1
;
if
(
paramInt
==
this
.
size
)
{
localNode1
=
null
;
localObject1
=
this
.
last
;
}
else
{
localNode1
= node(
paramInt
);
localObject1
=
localNode1
.
prev
;
}
for
(Object
localObject2
:
arrayOfObject1
)
{
Object
localObject3
=
localObject2
;
Node
localNode2
=
new
Node((Node)
localObject1
,
localObject3
,
null
);
if
(
localObject1
==
null
) {
this
.
first
=
localNode2
;
}
else
{
((Node)
localObject1
).
next
=
localNode2
;
}
localObject1
=
localNode2
;
}
if
(
localNode1
==
null
)
{
this
.
last
= ((Node)
localObject1
);
}
else
{
((Node)
localObject1
).
next
=
localNode1
;
localNode1
.
prev
= ((Node)
localObject1
);
}
this
.
size
+=
i
;
this
.
modCount
+= 1;
return
true
;
}
取数据
public
E
getFirst
()
{
Node
localNode
=
this
.
first
;
if
(
localNode
==
null
) {
throw
new
NoSuchElementException();
}
return
localNode
.
item
;
}
public
E getLast()
{
Node
localNode
=
this
.
last
;
if
(
localNode
==
null
) {
throw
new
NoSuchElementException();
}
return
localNode
.
item
;
}
public
E
get
(
int
paramInt
)
{
checkElementIndex(
paramInt
);
return
node(
paramInt
).
item
;
}
取第一个或取最后一个是最好取的,但随机取就要遍历数组了
删除数据
public
E
removeFirst
()
{
Node
localNode
=
this
.
first
;
if
(
localNode
==
null
) {
throw
new
NoSuchElementException();
}
return
unlinkFirst(
localNode
);
}
public
E removeLast()
{
Node
localNode
=
this
.
last
;
if
(
localNode
==
null
) {
throw
new
NoSuchElementException();
}
return
unlinkLast(
localNode
);
}
public
E
remove
(
int
paramInt
)
{
checkElementIndex(
paramInt
);
return
unlink(node(
paramInt
));
}
这个集合有个特别的地方,他模仿栈定义了这两个方法
public
void
push
(E
paramE
)
{
addFirst(
paramE
);
}
public
E pop()
{
return
removeFirst();
}