数据结构
定义:数据结构是计算机存储、组织数据的方式。数据结构是指相互之间存在一种或多种特定关系的数据元素的集合。通常情况下,精心选择的数据结构可以带来更高的运行或者存储效率。数据结构往往同高效的检索算法和索引技术有关。
数据结构的研究方向:
- 线性表
- 队列
- 堆栈
- 树
- 图论
- 排序和算法
顺序表-ArrayList
ArrayList的使用场景有哪些?
适合大量的存取和删除操作
ArrayList遍历方式?
public void arrayList(List<String> lists){
/* 第一种遍历方式 */
System.out.print("for循环的遍历方式:");
for (int i = 0; i < lists.size(); i++) {
System.out.print(lists.get(i));
}
/* 第二种遍历方式 */
System.out.print("增强for循环:");
for (String list : lists) {
System.out.print(list);
}
System.out.println();
/* 第三种遍历方式 */
System.out.print("Iterator的遍历方式:");
for (Iterator<String> list = lists.iterator();
list.hasNext();) {
System.out.print(list.next());
}
}
ArrayList是如何自动添加以及如何顺序删除节点?
面试会出现这样的陷阱
/**
* 添加数组
*/
public void addList() {
ArrayList<String> lists = new ArrayList<String>();
lists.add("张三");
lists.add("张三");
lists.add("李四");
lists.add("王五");
lists.add("王五");
lists.add("赵六");
}
/**
* 第一种方法
* 移除字符串
*/
public static void remove(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (s.equals("张三")) {
list.remove(s);
}
}
}
查看源码
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
按一般执行路径会走到else路径下最终调用fastRemove(int index)方法,可以看到会执行System.arraycopy方法,遍历第二个元素字符串“张三”时符合删除条件,从数组中删除该元素,并且将后一个元素移(张三)至当前位置,导致下一次循环遍历时后一个字符串“张三”没有遍历到,所以无法删除。针对这种情况,解决方法:倒序删除
public static void remove(ArrayList<String> list) {
for (int i = list.size() - 1; i >= 0; i--) {
String s = list.get(i);
if (s.equals("张三")) {
list.remove(s);
}
}
}
/**
* 第二种方法
* 移除字符串
*/
public static void remove(ArrayList<String> list) {
for (String s : list) {
if (s.equals("张三")) {
list.remove(s);
}
}
}
增强for循环会触发Java.util.ConcurrentModificationException
查看源码
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
// Android-changed: Add "limit" field to detect end of iteration.
// The "limit" of this iterator. This is the size of the list at the time the
// iterator was created. Adding & removing elements will invalidate the iteration
// anyway (and cause next() to throw) so saving this value will guarantee that the
// value of hasNext() remains stable and won't flap between true and false when elements
// are added and removed from the list.
protected int limit = ArrayList.this.size;
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor < limit;
}
@SuppressWarnings("unchecked")
public E next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
int i = cursor;
if (i >= limit)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
limit--;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
增强for循环写法是对实际的Iterator、hasNext、next方法的简写。
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
要避免这种情况的出现,则在使用迭代器迭代时不要使用ArrayList的remove,改用Iterator的remove即可。
链表-LinkedList
定义:LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。LinkedList 实现 List 接口,能对它进行队列操作。
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。LinkedList 是非同步的。
ArrayList和LinkedList的区别?
- ArrayList是基于动态数组的数据结构,LinkedList基于链表的数据结构。
- 对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。
- 对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。
List总结:
- List是一个接口,它继承于Collection接口,代表着有序的队列。
- AbstractList是一个抽象类,你继承于AbstracCollection,AbstractList实现List接口中除了size()、get(int poisiton)之外的函数。
- AbstractSequentialList是一个抽象类,它继承于 AbstractList.AbstractSequentialList实现了“链表中,根据index索引值操作链表的全部函数”。
- ArrayList 、LinkedList、Vector、Stack是List的四个实现类。