Java作为一门广泛使用的编程语言,其源码的学习对于深入理解Java平台和应用开发至关重要。以下是一些阅读Java源码的笔记,旨在帮助你轻松入门。
1. Java源码概述
Java源码主要由Java编程语言编写,它定义了Java运行时环境(JRE)和Java虚拟机(JVM)的核心功能。理解Java源码有助于:
- 提高编程技巧
- 解决复杂问题
- 深入理解JVM机制
- 开发高性能的Java应用
2. Java源码结构
Java源码通常包括以下部分:
- java.lang包:包含Java语言的核心类,如String、System、Object等。
- java.util包:提供常用的数据结构和集合类,如List、Map、Set等。
- java.io包:提供输入输出流的类,用于处理文件和网络I/O。
- java.net包:提供网络通信的类,如Socket、ServerSocket等。
- java.sql包:提供数据库访问和管理的类。
3. 重要的Java类
3.1 Object类
Object是所有Java类的根类,它提供了几个核心方法,如equals()、hashCode()和toString()。
public class Object {
public boolean equals(Object obj) {
return (this == obj);
}
public int hashCode() {
return super.hashCode();
}
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
}
3.2 String类
String类是不可变的字符序列,是Java编程中最常用的类之一。
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
// 省略其他代码
}
3.3 Collection接口
Collection接口是Java集合框架的基础,它定义了集合类的基本行为。
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean retainAll(Collection<?> c);
boolean removeIf(Predicate<? super E> filter);
void clear();
}
4. 阅读Java源码的技巧
- 从简单的类开始:先从常用的类如String、System等开始,逐渐过渡到更复杂的类。
- 理解类之间的关系:通过查看类的继承关系和接口实现,理解类之间的相互依赖。
- 关注异常处理:异常处理是Java源码中的一个重要部分,通过阅读异常处理可以了解类的错误处理机制。
- 使用IDE:现代IDE(如IntelliJ IDEA、Eclipse)提供了强大的源码阅读功能,可以大大提高阅读效率。
5. 实例:阅读ArrayList源码
ArrayList是Java中常用的动态数组实现,其源码如下:
”`java
public class ArrayList
private static final long serialVersionUID = 8683452581122892189L;
private static final int DEFAULT_CAPACITY = 10;
private transient Object[] elementData;
private int size;
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ARRAY;
}
public ArrayList(int initialCapacity) {
if (initialCapacity >= 0) {
this.elementData = new Object[initialCapacity];
} else {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class) {
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
} else {
this.elementData = DEFAULT_EMPTY_ARRAY;
}
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size - 1; i >= 0; i--) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i >= 0; i--) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
public E remove(int index) {
rangeCheck(index);
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
public void add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
}
public E remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++) {
if (elementData[index] == null) {
fastRemove(index);
return null;
}
}
} else {
for (int index = 0; index < size; index++) {
if (o.equals(elementData[index])) {
fastRemove(index);
return o;
}
}
}
return null;
}
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean modified = false;
for (int index = 0; index < size; ) {
if (filter.test(elementData[index])) {
fastRemove(index);
modified = true;
} else {
index++;
}
}
return modified;
}
public void clear() {
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
return v;
} catch (CloneNotSupportedException e) {
// this should never happen
throw new InternalError(e);
}
}
public boolean addAll(Collection<? extends E> c) {
Objects.requireNonNull(c);
int cSize = c.size();
if (cSize == 0) {
return false;
}
ensureCapacityInternal(size + cSize);
c.toArray(elementData, size);
size += cSize;
return true;
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize == 0) {
return false;
}
ensureCapacityInternal(size + cSize);
Object[] elementData = this.elementData;
System.arraycopy(c.toArray(), 0, elementData, index, cSize);
size += cSize;
return true;
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
for (int i = 0; i < size; ) {
if (!c.contains(elementData[i])) {
fastRemove(i);
modified = true;
} else {
i++;
}
}
return modified;
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
for (int i = 0; i < size; ) {
if (c.contains(elementData[i])) {
fastRemove(i);
modified = true;
} else {
i++;
}
}
return modified;
}
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = this.size;
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked")
E element = (E) elementData[i];
action.accept(element);
}
}
public void forEachOrdered(Consumer<? super E> action) {
final int size = this.size;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
@SuppressWarnings("unchecked")
final Consumer<? super E> actionToUse = action;
for (int i = 0; modCount == expectedModCount && i < size; i++) {
actionToUse.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, false);
}
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean modified = false;
for (int i = 0; i < size; ) {
if (filter.test(elementData[i])) {
fastRemove(i);
modified = true;
} else {
i++;
}
}
return modified;
}
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int size = this.size;
for (int i = 0; i < size; i++) {
elementData[i] = operator.apply(elementData[i]);
}
}
public void sort(Comparator<? super E> c) {
final int size = this.size;
@SuppressWarnings("unchecked")
E[] a = elementData;
int n = (size >= 1) ? size : 0;
Arrays.sort(a, 0, n, c);
}
public void sort(int fromIndex, int toIndex, Comparator<? super E> c) {
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) {
throw new ArrayIndexOutOfBoundsException();
}
@SuppressWarnings("unchecked")
E[] a = elementData;
int n = toIndex - fromIndex;
if (n > 1) {
Arrays.sort(a, fromIndex, fromIndex + n, c);
}
}
public List<E> subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) {
throw new ArrayIndexOutOfBoundsException();
}
return new ArrayList<>(this, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index >= size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index);
}
private void ensureCapacityInternal(int minimumCapacity) {
if (minimumCapacity - elementData.length > 0) {
grow(minimumCapacity);
}
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
if (newCapacity - MAX_ARRAY_SIZE > 0) {
newCapacity = hugeCapacity(minCapacity);
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) {
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
private void fastRemove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
}
@Override
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
@Override
public E remove(int index) {
rangeCheck(index);
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
@Override
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int cSize = a.length;
if (cSize == 0) {
return false;
}
ensureCapacityInternal(size + cSize);
int oldSize = elementData.length;
System.arraycopy(elementData, index, elementData, index + cSize, oldSize - index);
System.arraycopy(a, 0, elementData, index, cSize);
size += cSize;
return true;
}
@Override
public Iterator<E> iterator() {
return new Itr();
}
@Override
public ListIterator<E> listIterator(int index) {
return new Itr(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return new ArrayList<>(this, fromIndex, toIndex);
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last returned element
int expectedModCount = modCount;
Itr() {}
Itr(int index) {
cursor = index;
}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
E x = (E) elementData[i];
cursor = i + 1;
lastRet = i;
return x;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
private class ListItr implements ListIterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last returned element
int expectedModCount = modCount;
ListItr(int index) {
cursor = index;
}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
E x = (E) elementData[i];
cursor = i + 1;
lastRet = i;
return x;
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
E x = (E) elementData[i];
cursor = i;
lastRet = i;
return x;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
ArrayList.this.set(lastRet, e);
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
private static class ArrayListSpliterator<E> implements Spliterator<E> {
private final ArrayList<E> list;
private int index;
private int fence;
private int expectedModCount;
ArrayListSpliterator(ArrayList<E> list, int origin, int fence, boolean
