This question already has answers here:
How to compare two double values in Java?
(7 answers)
Closed 11 months ago.
I was messing around with data structures and while creating a Dynamic Array in Java from scratch, I figured out that my delete method (in the DynamicArray class) was not working for doubles.
I've read some documentation and I realized that doubles in Java are treated differently when it comes to comparison.
So I found ways to compare just doubles, but what do you do when the comparison is part of random data (Object type)?
Here is my code:
---Main---
public class Main {
public static void main(String[] args) {
//ArrayList<String> dynamicArray = new ArrayList<>();
DynamicArray dynamicArray = new DynamicArray();
System.out.println(dynamicArray.isEmpty());
dynamicArray.add(7);
dynamicArray.add(15);
dynamicArray.add(13);
dynamicArray.add("A");
dynamicArray.add('C');
dynamicArray.add(3.14159);
System.out.println("size: "+ dynamicArray.size());
System.out.println("capacity: "+ dynamicArray.capacity());
System.out.println(dynamicArray.toString());
dynamicArray.insert(2, "Hello");
System.out.println(dynamicArray.toString());
dynamicArray.delete(3.14159);
System.out.println("After removing 3.14159: "+ dynamicArray.toString( ));
dynamicArray.delete(7);
System.out.println(dynamicArray.toString());
}
}
---DynamicArray---
public class DynamicArray {
final double EPSILON = 0.000001d;
private int size;
private int capacity = 7;
Object[] array; // created an array of Objects named array
public DynamicArray() {
this.array = new Object[capacity];
}
public DynamicArray(int capacity) {
this.capacity = capacity;
this.array = new Object[capacity];
}
public void add(Object data) {
if (size >= capacity) {
grow();
}
array[size] = data;
size++;
}
public void insert(int index, Object data) {
if (size >= capacity) {
grow();
}
for (int i = size; i > index; i--) {
array[i] = array[i-1];
}
array[index] = data;
size++;
}
public void delete(Object data) {
for(int i = 0; i < size; i++) {
if(array[i] == data) {
for(int j = 0; j < (size - i - 1); j++){
array[i + j] = array[i + j + 1];
}
array[size - 1] = null;
size--;
if(size <=(int) (capacity/3)) {
shrink();
}
break;
}
}
}
public int search(Object data) {
return -1;
}
public void grow() {
}
public void shrink() {
}
public boolean isEmpty() {
return size == 0;
}
public Object peek() {
return array[size-1];
}
public String toString() {
String string = "[";
for (int i = 0; i < capacity; i++) {
string += array[i] + ", ";
}
if (string != "[") {
string = string.substring(0,string.length()-2);
}
return string+"]";
}
public int size() {
return size;
}
public int capacity() {
return capacity;
}
}
Am I missing something?
Objects in Java must be compared with equals(), not ==.
public void delete(Object data) {
for(int i = 0; i < size; i++) {
if(array[i] == data) {
for(int j = 0; j < (size - i - 1); j++){
The if(array[i] == data) will compare object references, not the objects' values.
you can use equals method of object, this way you don't need to use comparisons but you should check for null values.
public void delete(Object data) {
for(int i = 0; i < size; i++) {
if(array[i]!=null && array[i].equals(data)) {
for(int j = 0; j < (size - i - 1); j++){
array[i + j] = array[i + j + 1];
}
array[size - 1] = null;
size--;
if(size <=(int) (capacity/3)) {
shrink();
}
break;
}
}
}
Related
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;
}
}
I have a jagged array.
How can I override next(), so I can get its elements step-by-step?
This might be a wrong answer to your question. I'll remove it in that case, but maybe you can use it for what you want to achieve:
int[][] it = {{1,2}, {3,4,5}};
OfInt iterator = Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).iterator();
iterator.forEachRemaining((IntConsumer) System.out::print);
Stream the jagged array, flatmap it into one single IntStream and then do what you want with it. In this example I fetched the iterator but you might only want:
Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).forEach((IntConsumer) System.out::print);
In forEach you can do what you need, or use some other method of IntStream
Thank you all for your answers, I've found my answer in russian stackoverflow:
https://ru.stackoverflow.com/questions/867881/java-iterator-%D0%B4%D0%BB%D1%8F-%D0%BC%D0%BD%D0%BE%D0%B3%D0%BE%D0%BC%D0%B5%D1%80%D0%BD%D0%BE%D0%B3%D0%BE-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%D0%B0
public class IteratorFor2DArray implements Iterator {
private int size;
private int i = 0;
private int j = 0;
private int[][] values = new int[i][j];
private int position = 0;
public IteratorFor2DArray(int[][] values) {
this.values = values;
this.size = countOfElements(values);
}
private int countOfElements(int[][] values) {
int count = 0;
for (int[] row : values) {
count += row.length;
}
return count;
}
#Override
public boolean hasNext() {
return position < size;
}
#Override
public Integer next() {
if (position >= size) {
throw new NoSuchElementException();
}
int element = values[i][j];
position++;
j++;
while (i < values.length && j >= values[i].length) {
j = 0;
i++;
}
return element;
}
}
I've also found another way:
public class IteratorFor2DArray implements Iterator {
private int[][] data;
private int i, j;
public IteratorFor2DArray(int[][] data) {
this.data = data;
}
#Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int element = data[i][j];
j++;
while (i < data.length && j >= data[i].length) {
j = 0;
i++;
}
return element;
}
#Override
public boolean hasNext() {
return (i < data.length && j < data[i].length);
}
}
I am developing a big example case for teaching generics. A group of classes and interfaces that mimic the collections class in Java. Here's one of the source files:
package edu.brandeis.cosi12b.listdemo;
public class ArrayList<E extends Comparable<E>> extends AbstractList<E> implements List<E> {
private E[] list;
private int size;
private int capacity;
public ArrayList() {
this(20);
}
#SuppressWarnings("unchecked")
public ArrayList(int initialCapacity) {
list = (E[]) (new Object[initialCapacity]);
size = 0;
capacity = initialCapacity;
}
public int capacity() {
return capacity;
}
public int size() {
return size;
}
public void add(E val) {
list[size] = val;
size++;
}
public String toString() {
StringBuffer s = new StringBuffer();
s.append("[");
for (int i = 0; i < size - 1; i++) {
s.append(list[i]);
s.append(", ");
}
s.append(list[size - 1]);
s.append("]");
return (s.toString());
}
public void set(int index, E value) {
expandIfNecessary(index);
for (int i = size; i > index; i--) {
list[i] = list[i - 1];
}
list[index] = value;
if (index > size)
size = index + 1;
}
#SuppressWarnings("unchecked")
private void expandIfNecessary(int index) {
if (index < capacity)
return;
int newCapacity = capacity * 2 + index;
E[] oldArray = list;
list = (E[]) (new Object[newCapacity]);
for (int i = 0; i < size; i++)
list[i] = oldArray[i];
capacity = newCapacity;
}
public E get(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException("i: " + index + " s: " + size);
return list[index];
}
public void remove(int index) {
for (int i = index; i < size; i++)
list[i] = list[i + 1];
size--;
}
public boolean isEmpty() {
return size() == 0;
}
public int indexOf(E value) {
for (int i = 0; i < size; i++) {
if (list[i] == value)
return i;
}
return -1;
}
public boolean contains(E value) {
return (indexOf(value) != -1);
}
#Override
public void add(int index, E value) {
// TODO Auto-generated method stub
}
}
When I run this in a test case I get this error. I know it's something pretty subtle and it exceeds my knowledge of Java.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at edu.brandeis.cosi12b.listdemo.ArrayList.<init>(ArrayList.java:14)
at edu.brandeis.cosi12b.listdemo.ArrayList.<init>(ArrayList.java:9)
at edu.brandeis.cosi12b.listdemo.TestSuite.arrayListtest1(TestSuite.java:134)
at edu.brandeis.cosi12b.listdemo.TestSuite.runArrayListTests(TestSuite.java:15)
at edu.brandeis.cosi12b.listdemo.TestSuite.runAll(TestSuite.java:9)
at edu.brandeis.cosi12b.listdemo.ListDemo.runTests(ListDemo.java:13)
at edu.brandeis.cosi12b.listdemo.ListDemo.main(ListDemo.java:6)
Use
list = (E[]) new Comparable<?>[initialCapacity];
and
list = (E[]) (new Comparable<?>[newCapacity]);
Java doesn't have fully reified generics at runtime (it uses erasure), so it doesn't actually know what E is - only that it extends Comparable, so that is what the compiler inserts for the casts.
The bytecode generated by the compiler for your code looks like this if decompiled:
list (Comparable[]) new Object[initialCapacity];
which fails.
I am reading from SQLite in android some name of Files, I have like 3000 names that are added to an ArrayList but I discovered that I can't have more than 1000.
Is 1000 maximum size of an ArrayList<String> ? Searching over the internet I found that depends.
I found some math operations here (http://www.coderanch.com/t/524745/java/java/Maximum-capacity-arrayList-String-objects ) with 1000, and I found that the maximum capacity of an ArrayList<String> is given by Java Virtual Machine Memory.
Is there a way how to increase this ?
I have created an arrayList, its unlimited. you can also manipulate it to your desire, its has all the basic features of an arraylist.
here is the code.
public class BetterArray<E> {
private E[] array;
private final int DEFAULT_ARRAY_SIZE = 10;
private int size;
private void copyArray(E[] copyFrom, E[] copyTo) {
for (int i = 0; i <= copyFrom.length-1; i++) {
copyTo[i] = copyFrom[i];
}
}
private void createAnotherArray(){
int newSize = 2 * array.length;
E[] newArray = (E[])(new Object[newSize]);
copyArray(array, newArray);
array = newArray;
}
public BetterArray() {
array = (E[]) (new Object[DEFAULT_ARRAY_SIZE]);
this.size = 0;
}
public E get(int index){
if(index < 0 || index > size){
throw new RuntimeException("index not valid");
}
else{
return array[index];
}
}
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
public void insert(int position, E element) {
if(isFull())
createAnotherArray();
E previous_temp = get(position);
array[position]= element;
for(int k = position+1; k<= size; k++){
E current_temp = get(k);
array[k] = previous_temp;
previous_temp = current_temp;
}
size++;
}
public void append(E element) {
insert(size, element);
}
public void remove(int index){
for (int i = index; i <= size-1; i++){
array[i] = get(i+1);
}
size--;
}
public void shift(E element){
insert(0, element);
}
public boolean isFull() {
if (size == array.length)
return true;
return false;
}
public int size(){
return size;
}
public String toString(){
StringBuilder returnString = new StringBuilder();
for(int i= 0; i <= size-1; i++){
returnString.append(get(i).toString() + ", ");
}
return returnString.toString();
}
// public int index(E element){
// return 1;
// }
public void reverse(){
E temp_storage;
int halfSize = (size/2) ;
for (int k= 0; k<= halfSize; k++ ){
temp_storage = array[k];
array[k] = array[size-k-1];
array[size-k-1] = temp_storage;
}
}
}
import java.util.Random;
public class TestBed {
public static void main(String a[]) {
// creating the array
int[] array = new int[100];
Random random = new Random();
// changing the variable of my clone array for reference
int[] arr = cloneArray(array);
for (int i1 = 0; i1 < 100; i1++)
array[i1] = random.nextInt(100) + 1;
// print out of bubble sort before and after the sort
System.out
.println("***********************Bubble Sort ****************************");
arr = cloneArray(array);
System.out.println("Values Before the sort:\n");
printArray(arr);
System.out.println();
bubble_srt(arr);
System.out.print("Values after the sort:\n");
printArray(arr);
// print out of selection sort before and after the sort
System.out.println();
System.out
.println("********************Selection Sort*****************************");
System.out.println(" Selection Sort\n\n");
arr = cloneArray(array);
System.out.println("Values Before the sort:\n");
printArray(arr);
System.out.println();
selection_srt(arr);
System.out.print("Values after the sort:\n");
printArray(arr);
System.out.println();
Stack stack = new Stack();
}
public static int[] buildArray(int bound) {
return null;
}
// clone array as a data type
public static int[] cloneArray(int[] data) {
return (int[]) data.clone();
}
// print array as a data type
public static void printArray(int[] data) {
// while there are still numbers left in the array print out the next
// value
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
}
// bubble syntax
public static void bubble_srt(int a[]) {
int t = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < (a.length - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
// selection syntax
public static void selection_srt(int array[]) {
for (int x = 0; x < array.length; x++) {
int index_of_min = x;
for (int y = x; y < array.length; y++) {
if (array[index_of_min] > array[y]) {
index_of_min = y;
}
}
int temp = array[x];
array[x] = array[index_of_min];
array[index_of_min] = temp;
}
}
}
From here i have to link my stack class but i don't know how to get the 2 classes together correctly im new to programming and my school threw me into a java class that was to high for me and now im stuck 5 weeks in.
public class Stack {
Node top;
int size;
public Stack() {
top = null;
size = 0;
}
public int pop() {
if (top != null) {
int item = top.data;
top = top.next;
size--;
return item;
}
return -1;
}
public void push(int data) {
Node t = new Node(data);
t.next = this.top;
this.top = t;
size++;
}
public boolean isEmpty() {
return size <= 0;
}
public int getSize() {
return size;
}
public int peek() {
return top.data;
}
public void printStack() {
Node n = this.top;
int pos = this.getSize();
while (pos > 0) {
System.out.println("Position: " + pos + " Element: " + n.data);
if (pos > 0) {
n = n.next;
}
pos--;
}
}
}
class Node {
public int data;
public Node next;
Node(int d) {
data = d;
next = null;
}
public int getData() {
return data;`enter code here`
}`enter code here`
{
Stack s = new Stack();
s.push(9);
s.push(2);
s.push(7);
s.push(3);
s.push(6);
s.push(4);
s.push(5);
System.out.println("Size is: " + s.getSize());
// s.printStack();
int size = s.getSize();
for (int i = 0; i < size; i++) {
System.out.print(s.pop() + " ");
}
}
}
At the beginning of Stack class file, create a package name, eg:
package com.example.testcode;
Then in your TestBed class file, import your Stack class from the package, eg:
import com.example.testcode.Stack;