How to use iterators in java? - 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.

Related

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

Automatic increment array java

Hello I have got this basically fully working sorted vector , the problem here is however that I can only initialize the array to a fixed size before inserting any values , so for example I can initialize 5 but if I want to insert 6 items it gives me a null pointer exception .
I think I do understand what is happening however I would like anybody to show me a solution how the array size can be increased automatically every time I want to insert something .
( Without having to use any inbuilt java functionalities like ArrayList )
Thank you
package ads2;
public class SortedVector2
{
private int length;
private int maximum;
private int growby;
private int temp;
private int x = 0;
private int high;
private int middle;
private int low;
String[] data;
public SortedVector2()
{
length = 0;
maximum = 5;
data = new String[maximum];
}
public void AddItem(String value)
{
/*if (length == maximum)
{
maximum += 200000;
*/
data[length] = value;
length++;
// SetSorted();
// SetSorted(data);
}
public void SetSorted()
{
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
// private String[] data;
/*
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
} for (String s : data) {
System.out.println(s);
}
*/
}
public void SetGrowBy(int growby)
{
maximum += growby;
}
public int GetCapacity()
{
return maximum;
}
public int GetNoOfItems()
{
return length;
}
public String GetItemByIndex(int index)
{
return data[index];
}
public int FindItem(String search)
{
for (x=0;x<=length; )
{
middle =((low + high)/2);
if (data[middle].compareTo(search)==0)
{
return middle;
}
else if (data[middle].compareTo(search)<0)
{
low = middle;
x++;
return FindItem(search);
}
else
{
high = middle;
x++;
return FindItem(search);
}
}
return -1;
}
public boolean Exists(String search)
{
boolean output;
int y;
y = 0;
while (data[y] != search && (length - 1) > y)
{
++y;
}
if (data[y] == search)
{
output = true;
} else
{
output = false;
}
y = 0;
return output;
}
public void InsertItem(int index, String value)
{
if (length == maximum)
{
maximum += 200000;
}
for(int i = length - 1; i >= index; --i)
{
data[i + 1] = data[i];
}
data[index] = value;
length++;
}
public void DeleteItem(int index)
{
for(int x = index; x < length - 2; ++x)
{
data[x] = data[x + 1];
}
length--;
}
public String toString()
{
String res = "";
for (int i=0; i<length; i++)
res+=data[i] + "; ";
return res;
}
}
You have to do what the implementers of ArrayList did. When you try to add an element when the array is full, you create a larger array, copy the existing elements to it and add the new element.
To increase array size dynamically use Collection framework interface List,
It has implementation ArrayList,Vector and LinkedList use any one in them.
Or, Simply create copyArray(String[]) api which will give you array with increased capacity.
public String[] copyArray(String[] oldArray){
int capacity = oldArray.length * 2;
return Arrays.copyOf(oldArray, capacity);
}
String[] data = copyArray(data) // pass array
I think you've got all the basic variables you need to do what you need to do: just check if the size equals the capacity when you are adding an item and if it does reallocate the array:
if (size == capacity) {
capacity += growby;
data = Arrays.copyOf(data, capacity);
}
That's pretty much all ArrayList does.
You need to re-allocate when increasing the size of the data buffer, for example,
public void InsertItem(int index, String value)
{
String[] data2;
if (length == (maximum-1))
{
maximum += 5; // increment size in lot of 5
data2 = new String[maximum);
for (int ii = 0; ii < length; ii++)
{
data2[ii] = date[ii];
}
data = data2; // re-assign with increased size
}
for(int i = length - 1; i >= index; --i)
{
data[i + 1] = data[i];
}
data[index] = value;
length++;
}
In software engineering there is a saying, "Don't reinvent the wheel" - which emphasizes us on using the existing archetype. Because they are tested and used by for long period of time. So it's better to use ArrayList for regular/professional purpose.
But it if it is for learning purpose then you can chose any one from the previous answers.

Make And Show All Permutations of An Integer Array [duplicate]

This question already has answers here:
Algorithm to find next greater permutation of a given string
(14 answers)
Closed 8 years ago.
I am currently making a Permutation class for java. One of my methods for this class, is advance(), where the computer will take the array, and then display all permutations of the array.
So, for example, if I give the array {0,1,2,3,4,5}, or the number 6, it should give me from 012345.....543210.
Here is the code I have so far:
import java.util.*;
public class Permutation extends java.lang.Object {
public static int[] permutation;
public static int[] firstPerm;
public static int[] lastPerm;
public static int length;
public static int count;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public Permutation(int n) {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
}
public Permutation(int[] perm) {
length = perm.length;
permutation = new int[length];
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
throw new IllegalArgumentException("INVALID ELEMENT");
}
if (t[perm[i]]) {
throw new IllegalArgumentException("DUPLICATE VALUES");
}
t[perm[i]] = true;
permutation[i] = perm[i];
}
}
public void advance() {
}
public int getElement(int i) {
return permutation[i];
}
public boolean isFirstPerm() {
firstPerm = new int[permutation.length];
for (int i = 0; i < permutation.length; i++) {
firstPerm[i] = permutation[i];
}
Arrays.sort(firstPerm);
if (Arrays.equals(firstPerm, permutation)) {
return true;
} else {
return false;
}
}
public boolean isLastPerm() {
lastPerm = new int[firstPerm.length];
for (int i = 0; i < firstPerm.length; i++) {
lastPerm[i] = firstPerm[firstPerm.length - 1 - i];
}
if (Arrays.equals(permutation, lastPerm)) {
return true;
} else {
return false;
}
}
public static Permutation randomPermutation(int n) {
if (n <= 0) {
throw new IllegalArgumentException("INVALID NUMBER");
} else {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
Collections.shuffle(Arrays.asList(permutation));
return new Permutation(permutation);
}
}
public void reset() {
Arrays.sort(permutation);
}
public boolean isValid(int[] perm) {
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
return false;
}
if (t[perm[i]]) {
return false;
}
}
return true;
}
public int[] toArray() {
return permutation;
}
public String toString() {
StringBuffer result = new StringBuffer();
for (int i = 0; i < permutation.length; i++) {
result.append(permutation[i]);
}
String perms = result.toString();
return perms;
}
public static long totalPermutations(int n) {
count = 1;
for (int i = 1; i <= n; i++) {
count = count * i;
}
return count;
}
}
As you can see, the advance() method is the last thing I need to do, but I can't figure it out. Any help will be grand.
One of methods you can employ is:
Fix the first element and recursively find all permutations of rest of the array.
Then change the first elements by trying each of the remaining elements.
Base case for recursion is when you travel the entire length to get 0 element array. Then, either print it or add it to a List which you can return at the end.
public void advance() {
int[] temp = Arrays.copyOf(arr, arr.length);
printAll(0,temp);
}
private void printAll(int index,int[] temp) {
if(index==n) { //base case..the end of array
//print array temp here
}
else {
for(int i=index;i<n;i++) {//change the first element stepwise
swap(temp,index,i);//swap to change
printAll(index+1, temp);//call recursively
swap(temp,index,i);//swap again to backtrack
}
}
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
The way your code looks right now, it sounds like you want to be able to control the permutation class externally, rather than only supporting the one operation of printing all the permutations in order.
Here's an example of how to calculate a permutation.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static int factorial(int x) {
int f = 1;
while (x > 1) {
f = f * x;
x--;
}
return f;
}
public static List<Integer> permute(List<Integer> list, int iteration) {
if (list.size() <= 1) return list;
int fact = factorial(list.size() - 1);
int first = iteration / fact;
List<Integer> copy = new ArrayList<Integer>(list);
Integer head = copy.remove(first);
int remainder = iteration % fact;
List<Integer> tail = permute(copy, remainder);
tail.add(0, head);
return tail;
}
public static void main(String[] args) throws IOException {
List<Integer> list = Arrays.asList(4, 5, 6, 7);
for (int i = 0; i < 24; i++) {
System.out.println(permute(list, i));
}
}
}
Just to elaborate, the idea behind the code is to map an integer (iteration) to a particular permutation (ordering of the list). We're treating it as a base-n representation of the permutation where each digit represents which element of the set goes in that position of the resulting permutation.
For example, if we're permuting (1, 2, 3, 4) then we know there are 4! permutations, and that "1" will be the first element in 3! of them, and it will be followed by all permutations of (2, 3, 4). Of those 3! permutations of the new set (2, 3, 4), "2" will be the first element in 2! of them, etc.
That's why we're using / and % to calculate which element goes into each position of the resulting permutation.
This should work, and it's pretty compact, only drawback is that it is recursive:
private static permutation(int x) {
if (x < 1) {
throw new IllegalArgumentException(x);
}
LinkedList<Integer> numbers = new LinkedList<>();
for (int i = 0; i < x; i++) {
numbers.add(i);
}
printPermutations(numbers, new LinkedList<>());
}
private static void printPermutations(
LinkedList<Integer> numbers, LinkedList<Integer> heads) {
int size = numbers.size();
for (int i = 0; i < size; i++) {
int n = numbers.getFirst();
numbers.removeFirst();
heads.add(n);
printPermutations(numbers, heads);
numbers.add(n);
heads.removeLast();
}
if (numbers.isEmpty()) {
String sep = "";
for (int n : heads) {
System.out.print(sep + n);
sep = " ";
}
System.out.println("");
}
}

Recursive binary search in an int array using only 1 parameter

How can i implement a recursive binary search in an int array using only 1 parameter in java ?
it tried but my code doesn't work. I implemented a class which its instances are objects having arrays and a count variable to detect how many elements are their in the array. any idea how can i implement the recursive binary search using only 1 parameter ?
public class LinearSortedArray {
int count;
int[] a;
public LinearSortedArray() {
count = 0;
}
public LinearSortedArray(int size) {
count = 0;
a = new int[size];
}
public static int[] copyingMethod(int startPoint, int endPoint,
LinearSortedArray arrayObj) {
int[] copyingArray = new int[endPoint - startPoint];
int j = startPoint;
for (int i = 0; i < copyingArray.length; i++) {
copyingArray[i] = arrayObj.a[j];
j++;
}
return copyingArray;
}
public int binarySearchRec(int x) {
if (count == 0) {
return -1;
}
int pivot = count / 2;
LinearSortedArray newArrayObj;
if (x > a[pivot]) {
newArrayObj = new LinearSortedArray(count - pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(pivot, count, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return pivot + newArrayObj.binarySearchRec(x);
} else if (x < a[pivot]) {
newArrayObj = new LinearSortedArray(pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(0, pivot, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return newArrayObj.binarySearchRec(x);
} else {
return pivot;
}
}
}
P.S.: The arrays are already sorted
Binary search really requires a range and a target value -- so if you're only passing one parameter, this has to be the target and this must encapsulate the array & range.
public class ArraySegment {
protected int[] array;
protected int boundLo;
protected int boundHi;
public class ArraySegment (int[] array) {
// entire array.
this( array, 0, array.length);
}
public class ArraySegment (int[] array, int lo, int hi) {
this.array = array;
this.boundLo = lo;
this.boundHi = hi;
}
public int binarySearch (int target) {
if (boundHi <= boundLo) {
return -1; // Empty; not found.
}
int pivot = (boundLo + boundHi) / 2;
int pivotEl = array[ pivot];
if (target == pivotEl) {
return pivot; // Found!
}
if (target < pivotEl) {
// recurse Left of pivot.
ArraySegment sub = new ArraySegment( array, boundLo, pivot);
return sub.binarySearch( target);
} else {
// recurse Right of pivot.
ArraySegment sub = new ArraySegment( array, pivot, boundHi);
return sub.binarySearch( target);
}
}
}
It's a little bit questionable what kind of result you should return -- there isn't a good answer with the question posed like this, as an "integer index" kinda defeats the purpose of the ArraySegment/ range wrapper, and returning an ArraySegment containing only the found value is also fairly useless.
PS: You really shouldn't be copying the array or it's contents, just passing round references to ranges on that array. Like java.lang.String is a range on a character array.
You could contrive a single-parameter by using the Value Object Pattern, where you pass one "wrapper" object, but the object has many fields.
For example:
class SearchParams {
int target;
int start;
int end;
SearchParams(t, s, e) {
target = t;
start = s;
end = e'
}
}
int search(SearchParams params) {
// some impl
return search(new SearchParams(params.target, a, b));
}
Technically, this is one parameter. Although it may not be in the spirit of the rules.

Trying to access an array from ArrayList

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.

Categories

Resources