java中list对象为null6_java学习笔记6 ArrayList和LinkedList

public void ensureCapacity(int minCapacity) {

modCount++;

int oldCapacity = elementData.length;

if (minCapacity > oldCapacity) {

Object oldData[] = elementData;

int newCapacity = (oldCapacity * 3)/2 + 1;

if (newCapacity < minCapacity)

newCapacity = minCapacity;

// minCapacity is usually close to size, so this is a win:

elementData =Arrays.copyOf(elementData, newCapacity);

}

}

(5)当删除元素时,会把数组内从被删除的元素后的所有元素,向前移动一位, 代价很高

public E remove(int index) {

RangeCheck(index);

modCount++;

E oldValue = (E) elementData[index];

int numMoved = size - index - 1;

if (numMoved > 0)

System.arraycopy(elementData, index+1, elementData, index,

numMoved);

elementData[--size] = null; // Let gc do its work

return oldValue;

}

(6)     注: ctr+sft+w 在Eclipse中关闭所有窗口

输入syso  按下ctr+/ ,会快捷输入 System.out.println();

输入main  按下ctr+/ ,会快捷输入 Public staitc void main(String[ ] args)

二   LinkedList 类使用注意事项

(1)  LinkedList在JDK中使用循环链表实现的,  LinkedList   内部增加一个元素

public void add(int index, E element) {

addBefore(element, (index==size ? header : entry(index)));

}

private Entry addBefore(E e, Entry entry) {

Entry newEntry = new Entry(e, entry, entry.previous);

newEntry.previous.next = newEntry;

newEntry.next.previous = newEntry;

size++;

modCount++;

return newEntry;

}

private static class Entry {

E element;

Entry next;

Entry previous;

Entry(E element, Entry next, Entry previous) {

this.element = element;

this.next = next;

this.previous = previous;

}

}

private Entry entry(int index) {

if (index < 0 || index >= size)

throw new IndexOutOfBoundsException("Index: "+index+

", Size: "+size);

Entry e = header;

if (index < (size >> 1)) {

for (int i = 0; i <= index; i++)

e = e.next;

} else {

for (int i = size; i > index; i--)

e = e.previous;

}

return e;

}

(2)内部减少一个元素

private E remove(Entry e) {

if (e == header)

throw new NoSuchElementException();

E result = e.element;

e.previous.next = e.next;

e.next.previous = e.previous;

e.next = e.previous = null;

e.element = null; size--;

modCount++;

return result;

}

三   Linkedlist  和 ArrayList 两者比较

(1) ArrayList  : 不利于频繁插入和删除

(2)LinkedList :   不利于搜素

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值