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;
}
}
Related
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);
}
}
I'm new in Java programming and I'm trying to write a method that orders an array in crescent or decrescent mode.
public static int[] orderArray(int[] v, boolean mode) {
int newArray[] = {};
for (int i=0; i<v.length; i++) if (mode) newArray[i] = getMin(v, i); else newArray[i] = getMax(v, i);
return newArray;
}
So in another class I put:
int[] myArray = {5,3,4,1,6};
//Call the method
int[] newOrdArray = Vettori.orderArray(myArray, true);
System.out.println(Vettori.printArray(newOrdArray, ","));
There are some methods that I wrote before and I'm using to reach my objective.
I mean the methods: printArray, getMin and getMax
public static int getMin(int[] v, int pos) { //getMin
int minimum = 0;
if (v.length>0)
for (int i=pos;i<v.length;i++) {
if(i==pos) minimum=v[i];
else if(v[i]<=minimum) minimum=v[i];
}
return minimum;
}
public static int getMax(int[] v, int pos) { //getMax
int max = 0;
if (v.length>0)
for (int i=pos;i<v.length;i++) {
if(i==pos) max=v[i];
else if(v[i]>=max) max=v[i];
}
return max;
}
public static String printArray(int[] v, String separator) { //printArray
String stampa = "";
if (v.length>0) {
boolean insert_sep = true;
for (int i=0;i<v.length;i++) {
insert_sep = v[i]!=v.length;
if (insert_sep) stampa+=Integer.toString(v[i])+separator;
else stampa+=Integer.toString(v[i]);
}
stampa = stampa.substring(0, stampa.length()-1);
} else stampa = "Invalid array!";
return stampa;
}
When I compile the code and try to ordinate the array, the program throws the java.lang.ArrayIndexOutOfBoundsException exception. I'm trying to find the issue in my code, but I can't...
Here the output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utili.Vettori.ordinaVettore(Vettori.java:335)
at mainProgram.main(mainProgram.java:24)
Initialize array in orderArray method before adding any elements:
int[] newArray = new int[v.length];
Your problem lies in the orderArray method where you have created an array of size 0 then attempted to access elements of it causing an ArrayIndexOutOfBoundsException.
Change line
int newArray[] = {};
to create a new integer array of the same size as your method parameter v.
int newArray[] = new int[v.length];
Your resulting method should look like this
public static int[] orderArray(int[] v, boolean mode) {
int newArray[] = new int[v.length];
for (int i=0; i<v.length; i++) if (mode) newArray[i] = getMin(v, i); else newArray[i] = getMax(v, i);
return newArray;
}
found your problem
int newArray[] = {};
for (int i=0; i<v.length; i++) if (mode) newArray[i] = getMin(v, i);
else newArray[i] = getMax(v, i);
you are creating empty array, and then try to access fields which are not exist
The problem is simple, on your "orderArray(int[] v, boolean mode)" method, you did not initialize your new array, and thus you get ArrayOutOfBoundException.
Here, you have to make these changes, I've commented out the errorneous line and added a new line for the array initialization;
// int newArray[] = {};
int newArray[] = new int[v.length];
The complete corrected code is as below;
public class TestArrayOrder {
public static void main(String[] args) {
int[] myArray = { 5, 3, 4, 1, 6 };
// Call the method
int[] newOrdArray = orderArray(myArray, true);
System.out.println(printArray(newOrdArray, ","));
}
public static int[] orderArray(int[] v, boolean mode) {
// int newArray[] = {}; //you should initialize the array
int newArray[] = new int[v.length]; // array initialization
for (int i = 0; i < v.length; i++)
if (mode)
newArray[i] = getMin(v, i);
else
newArray[i] = getMax(v, i);
return newArray;
}
public static int getMin(int[] v, int pos) { // getMin
int minimum = 0;
if (v.length > 0)
for (int i = pos; i < v.length; i++) {
if (i == pos)
minimum = v[i];
else if (v[i] <= minimum)
minimum = v[i];
}
return minimum;
}
public static int getMax(int[] v, int pos) { // getMax
int max = 0;
if (v.length > 0)
for (int i = pos; i < v.length; i++) {
if (i == pos)
max = v[i];
else if (v[i] >= max)
max = v[i];
}
return max;
}
public static String printArray(int[] v, String separator) { // printArray
String stampa = "";
if (v.length > 0) {
boolean insert_sep = true;
for (int i = 0; i < v.length; i++) {
insert_sep = v[i] != v.length;
if (insert_sep)
stampa += Integer.toString(v[i]) + separator;
else
stampa += Integer.toString(v[i]);
}
stampa = stampa.substring(0, stampa.length() - 1);
} else
stampa = "Invalid array!";
return stampa;
}
}
Here is the output for the "true" mode call of your orderArray method;
1,1,1,1,6
And the output for "false" mode;
6,6,6,6,6
Hope that it helps.
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
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.
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.