Trying to access an array from ArrayList - java

I'm trying to Sort an array from my ArrayList:
ArrayList<Integer> al = new ArrayList<Integer>();
al.insert(0, 4);
al.insert(1, 3);
al.insert(2, 2);
al.insert(3, 1);
SelectionSortWrappers<Integer> ss = new SelectionSortWrappers<Integer>();
ss.sort(al.elements);
ss.show(al.elements);
But when I try to access al.elements, I'm getting:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
Here is my SelectionSort Class:
public class SelectionSortWrappers<T>{
public <T extends Comparable<? super T>> void sort(T[] array){
int index;
for(int i = 0 ; i < array.length;i++){
index = i;
for(int j = i + 1; j < array.length; j++){
if (array[j].compareTo(array[index]) < 0){
index = j;
}
}
T smaller = array[index];
array[index] = array[i];
array[i] = smaller;
}
}
public void show(T[] array){
for(int i=0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
}
My ArrayList, i had to create, because is for my university project, i cannot use the Java one.
package Lists;
public class ArrayList<T> implements List<T> {
private static int MAX_SIZE = 10;
private static final int NOT_FOUND = -1;
public T[] elements;
protected int size;
public ArrayList() {
size = 0;
elements = (T[]) new Object[MAX_SIZE];
}
public T[] getArray(){
return elements;
}
public int find(T v) {
for(int i = 0; i < size; i++) {
if(v == elements[i]) {
return i;
}
}
return NOT_FOUND;
}
public T elementAt(int pos) {
if(pos >= 0 && pos < size) {
return elements[pos];
}
throw new InvalidArgumentException();
}
public void insert(int pos, T v) {
if (size == MAX_SIZE){
elements = Arrays.copyOf(elements, size * 2);
MAX_SIZE = size * 2;
}
if(pos == size) {
elements[size] = v;
}
else {
for(int i = size; i > pos; i--) {
elements[i] = elements[i-1];
}
elements[pos] = v;
}
size++;
}
public void remove(int pos) {
if(pos >= 0 && pos < size) {
for(int i = pos; i < size-1; i++) {
elements[i] = elements[i+1];
}
size--;
}
else {
throw new InvalidArgumentException();
}
}
public int size() {
return size;
}
public void show(boolean reverse) {
if (!reverse){
for(int i=0; i < size; i++){
System.out.print(elements[i] + " ");
}
} else {
for(int i=size; i >= 0; i--){
System.out.print(elements[i] + " ");
}
}
}
}
Where is the problem? My elements field is public.

You're running into the predictable erasure-versus-arrays problem caused by doing (T[]) new Object[MAX_SIZE]. You'll get a warning on that line -- that warning is warning you about exactly this problem.
Your ArrayList class is pretending an Object[] is a T[], but it really isn't -- the actual referenced array is still an Object[]. When you pull it out with al.elements, it tries to actually cast it to an Integer[] and fails.
You will have to do something ugly to deal with this -- like what the built-in java.util.Collection.toArray(T[]) has to do, for example. Alternately, you could write your sorting method to access your ArrayList directly instead of trying to work on its underlying array.

Related

How would I pass a primitive instead of an array pointer

I have a school assignment where I need to create a very basic clone of ArrayList in java. It only needs to work with strings and have minimal functionality (size, add, get). This is what I have so far. I realise that there is probably many things that could be improved, but right now I am trying to work on this error
Exception in thread "main" java.lang.NullPointerException
at pt2.ArrayListMine.expand(ArrayListMine.java:13)
at pt2.ArrayListMine.add(ArrayListMine.java:32)
at pt2.Driver.main(Driver.java:21
I think the problem is that when I call expand() instead of moving the strings from array to backup and then backup to array it is passing pointers, so after I call it I effectivly have array pointing to backup pointing to array. Im not shure if/how I could force it to pass the string instead of the pointer so I am hoping I can get some advice. Thanks!
package pt2;
public class ArrayListMine {
private String[] array;
private String[] backup;
private int array_size = 0;
public void ArrayListMine() {
array = new String[10];
}
private void expand() {
if(array_size == array.length) {
for(int l = 0; l < array.length; l++) {
backup[l] = array[l];
}
int new_size = (int) (array.length * 2);
array = new String[new_size];
for(int l = 0; l < backup.length; l++) {
array[l] = backup[l];
}
}
}
public int size() {
return array_size;
}
public void add(String value) {
array_size = array_size + 1;
System.out.println(array_size);
expand();
array[array_size - 1] = value;
}
public String get(int index) {
return array[index];
}
}
array is null. Because this
public void ArrayListMine() {
array = new String[10];
}
is not a constructor. Remove the void. Like,
public ArrayListMine() {
array = new String[10];
}
Next, use backup = Arrays.copyOf(array, array.length) to copy array to backup. Because this
backup[l] = array[l];
will also blow-up.
Initialise the back up with the array size before copying.
backup = new String[array.length]; in side expand method before copying to it.
public class ArrayListMine {
private String[] array;
private String[] backup;
private int array_size = 0;
public ArrayListMine() {
array = new String[10];
}
private void expand() {
if(array_size == array.length) {
backup = new String[array.length];
for(int l = 0; l < array.length; l++) {
backup[l] = array[l];
}
int new_size = (int) (array.length * 2);
array = new String[new_size];
for(int l = 0; l < backup.length; l++) {
array[l] = backup[l];
}
}
}
public int size() {
return array_size;
}
public void add(String value) {
array_size = array_size + 1;
System.out.println(array_size);
expand();
array[array_size - 1] = value;
}
public String get(int index) {
return array[index];
}
public static void main(String[] args) {
ArrayListMine arrayListMine = new ArrayListMine();
for(int i=0;i<=20;i++) {
arrayListMine.add("test "+i);
}
}
}
and further you can replace your for loop with System.arrayCopy
private void expand() {
if(array_size == array.length) {
backup = new String[array.length];
System.arraycopy(array, 0, backup, 0, array_size);
/*for(int l = 0; l < array.length; l++) {
backup[l] = array[l];
}*/
int new_size = (int) (array.length * 2);
array = new String[new_size];
/*for(int l = 0; l < backup.length; l++) {
array[l] = backup[l];
}*/
System.arraycopy(backup, 0, array, 0, array_size);
}
}

Java ArrayList String Selection Sort

I'm struggling mightly on doing selection sort on an ArrayList of Strings to alphabetize them. I have no idea what I'm doing wrong. But its just not working properly for me. Heres my code.
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("d");
list.add("f");
list.add("c");
System.out.println(list);
int i;
int j;
int minValue;
int minIndex;
for (i=0; i<list.size(); i++) {
System.out.println(list.get(i));
char iLetter = (list.get(i).charAt(0));
int iValue = (int) iLetter;
minValue = iValue;
minIndex = i;
for(j=i; j<list.size(); j++) {
char jLetter = list.get(j).charAt(0);
int jValue = (int) jLetter;
if (jValue < minValue) {
minValue = jValue;
minIndex = j;
}
}
if(minValue < iValue) {
int temp = iValue;
char idx = list.get(minIndex).charAt(0);
int idxValue = (int) idx;
iValue = idxValue;
idxValue = temp;
}
}
System.out.println(list);
}
It still prints it out as ["a", "d", "f", "c"]
You are not updating your list anywhere in your loop, so it remains unsorted.
In order to actually swap elements of the list, replace:
if(minValue < iValue) {
int temp = iValue;
char idx = list.get(minIndex).charAt(0);
int idxValue = (int) idx;
iValue = idxValue;
idxValue = temp;
}
with:
if(minValue < iValue) {
Collections.swap (list, i, minIndex);
}
Collections.swap performs the following modification:
list.set(i, list.set(minIndex, list.get(i)));
Now the output will be
[a, c, d, f]
As mentioned, you need to do the actual swapping in the list, not just the temporary variables (doh!).
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("d");
list.add("f");
list.add("c");
System.out.println(list);
for (int i = 0; i < list.size(); i++) {
String smallest = list.get(i);
int smallestIndex = i;
for (int j = i; j < list.size(); j++) {
String value = list.get(j);
if (value.compareTo(smallest) < 0) {
smallest = value;
smallestIndex = j;
}
}
if (smallestIndex != i) {
String head = list.get(i);
list.set(i, smallest);
list.set(smallestIndex, head);
}
}
System.out.println(list);
}
Additionally, your code is just a single method, AKA spaghetti code. To make it more object-oriented you could make the following changes.
import java.util.*;
public class SelectionSort<T extends Comparable> {
private List<T> values;
public SelectionSort(List<T> values) {
this.values = values;
}
private void sort() {
for (int headIndex = 0; headIndex < values.size(); headIndex++) {
sortFrom(headIndex);
}
}
private void sortFrom(int headIndex) {
int smallestIndex = findSmallestFrom(headIndex);
if (smallestIndex != headIndex) {
swap(headIndex, smallestIndex);
}
}
private int findSmallestFrom(int i) {
int smallestIndex = i;
T smallest = values.get(i);
for (int j = i; j < values.size(); j++) {
T value = values.get(j);
if (value.compareTo(smallest) < 0) {
smallest = value;
smallestIndex = j;
}
}
return smallestIndex;
}
private void swap(int i, int j) {
T head = values.get(i);
values.set(i, values.get(j));
values.set(j, head);
}
public static void main(String[] args) {
List<String> values = createTestData();
System.out.println(values);
SelectionSort selectionSort = new SelectionSort<>(values);
selectionSort.sort();
System.out.println(values);
}
private static List<String> createTestData() {
List<String> values = new ArrayList<>();
values.add("a");
values.add("d");
values.add("f");
values.add("c");
return values;
}
}
Some of the changes I made:
Separate method for creation of test data
Separate method for printing the before and after state of the list and calling the sort
Create an instance instead of only static code
separate iterations and logic into meaningful methods
Rename the 'list' variable to 'values'. The fact that it's a list is already clear. The convention is to name a collection by the meaning of the data it contains
Introduced a generic type variable on the class (<T extends Comparable>). This allows any type of data to be sorted, as long as it implements the Comparable interface

Returning a generic type in Java Hashtables

We're currently studying hashtables in our Java course.
The lecturer has set out a few methods for us to construct. The first two are fine but I'm struggling with "public E max()". Most stuff I have read seems to indicate you can't instantiate a generic type, so I'm struggling to see how I can write this method for a hashtable.
The objective is of course to return the largest value in the hashtable, which I think I could do if the type wasn't generic, but in this case it is.
Apologies if my code is a bit hard to read.
import java.lang.reflect.Array;
import java.util.*;
public class Assignment6_2015 {
public static void main(String[] args){
//=======================================================
// Question 1, test Point class by creating a hashlist of Point instances
HashList<Point> h1 = new HashList<Point>(5);
h1.add(new Point(1,2));
h1.add(new Point(2,4));
h1.add(new Point(2,4));
h1.add(new Point(2,4));
h1.add(new Point(3,8));
h1.add(new Point(3,8));
h1.add(new Point(7,3));
h1.add(new Point(9,10));
h1.add(new Point(9,10));
h1.add(new Point(9,10));
h1.add(new Point(9,10));
h1.add(new Point(9,10));
h1.displayLists();
//=======================================================
// Question 2, testing new methods
// ----- Frequency Method Test -----
System.out.println();
System.out.print("Frequency of Points (9,10): ");
System.out.println(h1.freq(new Point(9,10)));
System.out.println();
System.out.print("Frequency of Points (2,4): ");
System.out.println(h1.freq(new Point(2,4)));
System.out.println();
System.out.print("Frequency of Points (1,2): ");
System.out.println(h1.freq(new Point(1,2)));
// ----- End Frequency Method Test -----
System.out.println();
System.out.print("Table Size: ");
System.out.println(h1.tableSize());
System.out.print("All used?: ");
System.out.println(h1.allUsed());
System.out.print("Percentage used?: ");
System.out.println(h1.percentUsed());
}
}
//=======================================================
// class Point
class Point implements Comparable<Point>{
private int x,y;
Point(int a, int b){x = a; y = b;}
public int x(){return x;}
public int y(){return y;}
public String toString(){return "("+x+","+y+")";}
public boolean equals(Object ob){
Point p = (Point)ob;
if(x == p.x() && y == p.y()){
return true;
}
else{
return false;
}
}
public int compareTo(Point p){
if(x > p.x() && y > p.y()){
return 0;
}
else{
return -1;
}
}
public int hashCode(){
return x*y*31;
}
}
//End class Point
//=======================================================
//HashTable class
class HashList<E extends Comparable<E>>{
private GLinkedList<E> data[];
public HashList(int n){
data = (GLinkedList<E>[])(new GLinkedList[n]);
for(int j = 0; j < data.length;j++)
data[j] = new GLinkedList<E>();
}
private int hashC(E x){
int k = x.hashCode();
//an alternative is to mask the minus using
//int k = x.hashCode() & 0x7fffffff;
int h = Math.abs(k % data.length);
return(h);
}
public void add(E x){
int index = hashC(x);
data[index].add(x);
}
public boolean contains(E x){
int index = hashC(x);
return(data[index].contains(x));
}
public void displayLists(){
for(GLinkedList<E> k : data){
if(k.length() > 0)
k.display();
}
}
public void display(){
System.out.print("<");
int ind = 0;
while(ind < data.length){
Iterator<E> it = data[ind].iterator();
while(it.hasNext())
System.out.print(it.next()+" ");
ind++;
}
System.out.println(">");
}
public int tableSize(){
return data.length;
}
//===================================================================
//Add new methods for assignment here
public int freq(E x){
int freq = 0;
int index = hashC(x);
for(int j = 0; j < data[index].length();j++){
if(data[index].contains(x)){
freq++;
}
}
return freq;
}
public boolean allUsed(){
int total = data.length;
int inuse = 0;
for(int j = 0; j < data.length;j++){
if(data[j].length() >= 1){
inuse++;
}
}
if(inuse == total){return true;}
else{return false;}
}
public E max(){
int j = 0;
E y = // ???;
Iterator<E> it = data[j].iterator();
while(j<data.length){
it = data[j].iterator();
E x = it.next();
while(it.hasNext()){
if(data[j].iterator().next().compareTo(x) == 0){
x = it.next();
y = x;
}
}
j++;
}
return y;
}
//int x = (it.next().compareTo(largest));
//if(x == 0){largest = it.next();}
//====================================================================
public double percentUsed(){
int count = 0;
for(int j = 0; j < data.length; j++){
if(data[j].length() > 0)
count++;
}
double p = count *100.0 / data.length;
return p;
}
public int largestBucket(){
int max = 0;
for(int j = 0; j < data.length; j++)
if(data[j].length() > max) max = data[j].length();
return max;
}
public int smallestBucket(){
int min = data[0].length();
for(int j = 1; j < data.length; j++)
if(data[j].length() < min) min = data[j].length();
return min;
}
public int[] listSizes(){
int n = this.largestBucket();
int d[] = new int[n+1];
for(int j = 0; j < d.length; j++) d[j] = 0;
for(int j = 0; j < data.length; j++){
int m = data[j].length();
d[m] = d[m] + 1;
}
return d;
}
public int empty(){
int count = 0;
for(int j = 0; j < data.length; j++)
if(data[j].length() == 0) count++;
return count;
}
public Iterator<E> iterator(){
ArrayList<E> items = new ArrayList<E>();
int ind = 0;
while(ind < data.length){
Iterator<E> it = data[ind].iterator();
while(it.hasNext())
items.add(it.next());
ind++;
}
return items.iterator();
}
}
class GLinkedList<E extends Comparable<E>>{
private Node<E> head = null;//empty list
private int size = 0;
public void add(E x){ //add at head
Node<E> nw = new Node<E>(x);
nw.setNext(head);
head = nw;
size++;
}
public boolean contains(E x){
Node<E> k = head;
boolean found = false;
while(k != null && !found){
E kk = k.data();
if(kk.compareTo(x) == 0) found = true;
else k = k.next();
}
return found;
}
public void remove(E x){
Node<E> k = head; Node<E> bk = head;
boolean found = false;
while(k != null && !found){
if(k.data().compareTo(x) == 0) found = true;
else{ bk = k; k = k.next();}
}
if(found)
if(k == head)
head = k.next();
else
bk.setNext(k.next());
}
public int length(){
return size;
}
public void display(){
Node<E> k = head;
System.out.print('[');
while(k != null){
if(k.next != null)
System.out.print(k.data()+", ");
else
System.out.print(k.data());
k = k.next();
}
System.out.println(']');
}
public Iterator<E> iterator(){
return new GIterator<E>(head, size);
}
private static class GIterator<E extends Comparable<E>> implements Iterator<E>{
private Node <E> head;
private int size;
private int index = 0;
GIterator(Node<E> h, int s){
head = h; size = s;
}
public boolean hasNext(){
return index < size;
}
public E next(){
if(index == size) throw new NoSuchElementException();
E item = head.data();
head = head.next(); index++;
return item;
}
public void remove(){}
}
}
class Node<E extends Comparable<E>>{
E data;
Node<E> next;
public Node(E x){
data = x; next = null;
}
public Node<E> next(){return next;}
public void setNext(Node<E> p){
next = p;
}
public void set(E x){data = x;}
public E data(){return data;}
}
Currently at the moment, the max() method doesn't work, I've tried out a few things in it but I can't seem to get it to return a generic type no matter what way I approach it.
Why don't you write this
E y=null;
To clean up your code a little, help reduce complexity and avoid errors, you could use this snippet to iterate over all elements
for ( GLinkedList<E> d : data ) {
final Iterator<E> it = d.iterator();
while ( it.hasNext() ) {
final E currentElement = it.next();
// Insert logic here!
}
}
The Point class implements Comparable and since the HashList is composed of objects that are Comparable, you can use this property to compare each Point seen as a Comparable.
The logic of max() is something like:
declare max as a `Comparable`
for each linked-list `ll` in `data`
for each element `c` in `ll`
if `c.compareTo(max) >= 0` then
max <- c
endif
endfor
endfor
return max
You have to handle max initialisation either to null or to a first point in the hashlist, or to some point value that will be always inferior to any point, like Point(Integer.MIN_VALUE, Integer.MIN_VALUE).
You can edit these two lines in max method in a manner as follows:
E y = (E)data[0]; // ???;
int j = 1;
Above code change will resolve your problem. Also you have to put other null checks and etc. which are mentioned above in comments.
like
if(y==null) return null; //since there is no element in the array

Array based Deque implementation

I am following an online example and learning "Circular Deque implementation in Java using array". Here is the online resource that I am following:
Circular Queue Implementation
I have an array based deque class which has final capacity of 5. Now if the array is full then I can have the methods create a temporary array of all the objects and then copy all the objects of temporary array back to "object[] arr". I have been at it for some time now but have not been able to get it going. I would appreciate if someone can help me understand the process here please. I have following class methods:
insertAtFront()
insertAtLast()
size()
isEmpty()
toString()
Here is my code:
public class ArrayDeque {
private static final int INIT_CAPACITY = 5;
private int front;
private int rear;
private Object[] arr;
public ArrayDeque(){
arr = new Object[ INIT_CAPACITY ];
front = 0;
rear = 0;
}
public void insertAtFirst(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[front] = item;
++front;
}
public void insertAtLast(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[rear] = item;
++rear;
}
public int size(){
return (rear - front);
}
public boolean isEmpty(){
return (front == rear);
}
public String toString(){
String s = "";
for(int i = 0; i < size(); ++i)
s += arr[i] + "\n";
return s;
}
}//CLASS
Try the below code, i changed the logic a bit by keeping track of how much the array is filled up. Your main problem is with the size() function, which is giving wrong indications. Some optimization is pending for i see some nulls in the results.
public class ArrayDeque {
public static void main(String[] args) {
ArrayDeque t = new ArrayDeque ();
t.insertAtFirst("1");
t.insertAtFirst("2");
t.insertAtFirst("3");
t.insertAtFirst("4");
t.insertAtFirst("5");
t.insertAtFirst("6");
t.insertAtFirst("7");
t.insertAtFirst("8");
t.insertAtFirst("9");
t.insertAtFirst("10");
t.insertAtFirst("11");
t.insertAtFirst("12");
t.insertAtFirst("13");
t.insertAtFirst("14");
System.out.println("After first--"+t.toString());
t.insertAtLast("1");
t.insertAtLast("2");
t.insertAtLast("3");
t.insertAtLast("4");
t.insertAtLast("5");
t.insertAtLast("6");
t.insertAtLast("7");
t.insertAtLast("8");
t.insertAtLast("9");
t.insertAtLast("10");
t.insertAtLast("11");
t.insertAtLast("12");
t.insertAtLast("13");
t.insertAtLast("14");
System.out.println("After last--"+t.toString());
}
private static final int INIT_CAPACITY = 5;
private int NEW_CAPACITY;
private int ARRAY_SIZE;
private Object[] arr;
public TestClass(){
arr = new Object[ INIT_CAPACITY ];
NEW_CAPACITY = INIT_CAPACITY;
ARRAY_SIZE = 0;
}
public void insertAtFirst(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
}
public void insertAtLast(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 0; i < arr.length; ++i)
tmp[i] = (String)arr[i];
arr = tmp;
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
}
public int size(){
return ARRAY_SIZE;
}
public boolean isEmpty(){
return (ARRAY_SIZE == 0);
}
public String toString(){
String s = "";
for(int i = 0; i < arr.length; ++i)
s += arr[i] + "\t";
return s;
}
}

How to use iterators in java?

I have implemented Priority Queue interface for making heap. Can you tell me how to implement an iterator on the top of that? point me to some apropriate tutorial,i am new to java and on a very short deadline here.
Actually i need a method to find and modify an object from heap on the basis of Object.id. I dont care if it is O(n).
public interface PriorityQueue {
/**
* The Position interface represents a type that can
* be used for the decreaseKey operation.
*/
public interface Position {
/**
* Returns the value stored at this position.
* #return the value stored at this position.
*/
Comparable getValue();
}
Position insert(Comparable x);
Comparable findMin();
Comparable deleteMin();
boolean isEmpty();
int size();
void decreaseKey(Position p, Comparable newVal);
}
// BinaryHeap class
public class OpenList implements PriorityQueue {
public OpenList() {
currentSize = 0;
array = new Comparable[DEFAULT_CAPACITY + 1];
}
public OpenList(int size) {
currentSize = 0;
array = new Comparable[DEFAULT_CAPACITY + 1];
justtocheck = new int[size];
}
public OpenList(Comparable[] items) {
currentSize = items.length;
array = new Comparable[items.length + 1];
for (int i = 0; i < items.length; i++) {
array[i + 1] = items[i];
}
buildHeap();
}
public int check(Comparable item) {
for (int i = 0; i < array.length; i++) {
if (array[1] == item) {
return 1;
}
}
return array.length;
}
public PriorityQueue.Position insert(Comparable x) {
if (currentSize + 1 == array.length) {
doubleArray();
}
// Percolate up
int hole = ++currentSize;
array[ 0] = x;
for (; x.compareTo(array[hole / 2]) < 0; hole /= 2) {
array[hole] = array[hole / 2];
}
array[hole] = x;
return null;
}
public void decreaseKey(PriorityQueue.Position p, Comparable newVal) {
throw new UnsupportedOperationException(
"Cannot use decreaseKey for binary heap");
}
public Comparable findMin() {
if (isEmpty()) {
throw new UnderflowException("Empty binary heap");
}
return array[ 1];
}
public Comparable deleteMin() {
Comparable minItem = findMin();
array[ 1] = array[currentSize--];
percolateDown(1);
return minItem;
}
private void buildHeap() {
for (int i = currentSize / 2; i > 0; i--) {
percolateDown(i);
}
}
public boolean isEmpty() {
return currentSize == 0;
}
public int size() {
return currentSize;
}
public void makeEmpty() {
currentSize = 0;
}
private static final int DEFAULT_CAPACITY = 100;
private int currentSize; // Number of elements in heap
private Comparable[] array; // The heap array
public int[] justtocheck;
private void percolateDown(int hole) {
int child;
Comparable tmp = array[hole];
for (; hole * 2 <= currentSize; hole = child) {
child = hole * 2;
if (child != currentSize &&
array[child + 1].compareTo(array[child]) < 0) {
child++;
}
if (array[child].compareTo(tmp) < 0) {
array[hole] = array[child];
} else {
break;
}
}
array[hole] = tmp;
}
private void doubleArray() {
Comparable[] newArray;
newArray = new Comparable[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
array = newArray;
}
You might look at java.util.PriorityQueue. If you're in a hurry, Arrays.sort() may suffice. Once sorted, Arrays.binarySearch() becomes possible.
Your underlying data structure is an array, which is difficult to write a Java-style iterator for. You could try creating a container class implementing java.util.Iterator which holds a reference to your Comparable element and its current array index. You'll need to manually update the index when you move the container.

Categories

Resources