- package net.wastl.webmail.misc;
- import net.wastl.webmail.ui.ContentProvider;
- /**
- * ContentProviderHeap.java
- *
- * This class is a simple heap structure for generating a sorted order for
- * content providers.
- *
- * Created: Mon Oct 4 13:28:09 1999
- *
- * @author Sebastian Schaffert
- * @version
- */
- public class ContentProviderHeap {
- int num_entries;
- ContentProvider[] keys;
- public ContentProviderHeap(int capacity) {
- keys=new ContentProvider[capacity+1];
- num_entries=0;
- }
- protected ContentProviderHeap(int capacity,int num_entries,ContentProvider[] keys) {
- this(capacity);
- this.num_entries=num_entries;
- System.arraycopy(keys,0,this.keys,0,num_entries);
- }
- /**
- * Insert a key/value pair
- * Reorganize Heap afterwards
- */
- public void insert(ContentProvider key) {
- keys[num_entries]=key;
- num_entries++;
- increase(num_entries);
- }
- /**
- * Return and delete the key with the lowest long value. Reorganize Heap.
- */
- public ContentProvider next() {
- ContentProvider ret=keys[0];
- keys[0]=keys[num_entries-1];
- num_entries--;
- decrease(1);
- return ret;
- }
- public boolean isEmpty() {
- return num_entries==0;
- }
- /**
- * Remove an Object from the Heap.
- * Unfortunately not (yet) of very good complexity since we are doing
- * a simple linear search here.
- * @param key The key to remove from the heap
- */
- public void remove(ContentProvider key) {
- for(int i=0;i<num_entries;i++) {
- if(key.equals(keys[i])) {
- num_entries--;
- int cur_pos=i+1;
- keys[i]=keys[num_entries];
- decrease(cur_pos);
- break;
- }
- }
- }
- /**
- * Lift an element in the heap structure
- * Note that the cur_pos is actually one larger than the position in the array!
- */
- protected void increase(int cur_pos) {
- while(cur_pos > 1 && keys[cur_pos-1].getPreferredPosition()<keys[cur_pos/2-1].getPreferredPosition()) {
- ContentProvider tmp1=keys[cur_pos/2-1];keys[cur_pos/2-1]=keys[cur_pos-1];keys[cur_pos-1]=tmp1;
- cur_pos /= 2;
- }
- }
- /**
- * Lower an element in the heap structure
- * Note that the cur_pos is actually one larger than the position in the array!
- */
- protected void decrease(int cur_pos) {
- while((cur_pos*2 <= num_entries && keys[cur_pos-1].getPreferredPosition() > keys[cur_pos*2-1].getPreferredPosition()) ||
- (cur_pos*2+1 <=num_entries && keys[cur_pos-1].getPreferredPosition() > keys[cur_pos*2].getPreferredPosition())) {
- int lesser_son;
- if(cur_pos*2+1 <= num_entries) {
- lesser_son=keys[cur_pos*2-1].getPreferredPosition()<keys[cur_pos*2].getPreferredPosition()?cur_pos*2:cur_pos*2+1;
- } else {
- lesser_son=cur_pos*2;
- }
- ContentProvider tmp1=keys[cur_pos-1];keys[cur_pos-1]=keys[lesser_son-1];keys[lesser_son-1]=tmp1;
- cur_pos=lesser_son;
- }
- }
- public ContentProviderHeap getClone() {
- return new ContentProviderHeap(keys.length, num_entries,keys);
- }
- } // ContentProviderHeap