一、计算java对象在内存中占用的大小
来源:https://www.coursera.org/learn/algorithms-part1/supplement/mpK20/lecture-slides
二、实例说明:
以下为双向列队Deque.java
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private int size;
private final Node sentinel;
private class Node {
Node next;
Node prev;
Item item;
Node() {
}
Node(Item item, Node prev, Node next) {
this.item = item;
this.prev = prev;
this.next = next;
}
}
public Deque() {
sentinel = new Node();
sentinel.next = sentinel;
sentinel.prev = sentinel;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void addFirst(Item item) {
if (item == null) throw new IllegalArgumentException("Cannot add null");
Node newNode = new Node(item, sentinel, sentinel.next);
sentinel.next.prev = newNode;
sentinel.next = newNode;
size++;
}
public void addLast(Item item) {
if (item == null) throw new IllegalArgumentException("Cannot add null");
Node newNode = new Node(item, sentinel.prev, sentinel);
sentinel.prev.next = newNode;
sentinel.prev = newNode;
size++;
}
public Item removeFirst() {
if (size == 0) throw new NoSuchElementException("Stack underflow");
Item oldItem = sentinel.next.item;
sentinel.next.next.prev = sentinel;
sentinel.next = sentinel.next.next;
size--;
return oldItem;
}
public Item removeLast() {
if (size == 0) throw new NoSuchElementException("Stack underflow");
Item oldItem = sentinel.prev.item;
sentinel.prev.prev.next = sentinel;
sentinel.prev = sentinel.prev.prev;
size--;
return oldItem;
}
public Iterator<Item> iterator() {
return new DequeIterator();
}
private class DequeIterator implements Iterator<Item> {
private Node first;
private int count;
private DequeIterator() {
first = sentinel;
count = size();
}
@Override
public boolean hasNext() {
return !(count == 0);
}
@Override
public Item next() {
if (count == 0) throw new NoSuchElementException("Stack underflow");
Item item = first.next.item;
first = first.next;
count--;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException("the operation of remove is not supported");
}
}
- 当使用一Deque对象增加n个Item后,该Deque对象所占用的内存大小为:48n + 80 字节
- Object overhead: 16
- 内部类Node的大小: 48
- Object overhead:16
- 变量next,prev,Item: 3 * 8 = 24
- 外部类指针: 8
- padding:0
- 变量size: 4
- 变量sentinel: 8
- sentinel变量指向的Node对象: 48 * 1 = 48
- padding: 4
网友评论