Java Queue, entire Queue is replaced by new added element - java

I am working on a project for school that have jobs(an int array), i am new to Java and have encountered a strange error while trying to put these jobs in a Queue.
My problem is that once i already have one element in the Queue, the next element replaces the previous element in the queue,
i.e if Queue[0] holds arr1, and i add the next element ( Queue.add(arr2)), arr 2 gets added to Queue[1] but Queue also replaces Queue[0] with arr2.
There is a lot of code so i have only posted i am using and where the function where it is called, the element change happens as soon as .add is executed.
public class drumQueue {
private Queue<int[]> myQueue = new LinkedList<int[]>();
private static boolean drumIsBusy = false;
int index=0;
public void add(int[] p){
myQueue.add(p);
}
public void remove(){
myQueue.remove();
}
public int[] getP(){
System.out.println("POPED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return myQueue.poll();
}
public boolean isDrumIsBusy() {
return drumIsBusy;
}
public void setDrumIsBusy(boolean drumIsBusy) {
drumQueue.drumIsBusy = drumIsBusy;
}
public void print(){
for( int i =0 ;i < myQueue.size(); i++ ){
System.out.println(myQueue.peek()[1]+ "ELEMENT!!!!!!!!!!!!!!!");
}
}
public int size(){
return myQueue.size();
}
}
Method that uses above class in a different class.
private static void MemeoryManager(int[] a, int[] p) {
// TODO Auto-generated method stub
memoryLink.freeSpaceTableBuilder();
memoryLink.freeSpaceTableBuilder();
p[2] = memoryLink.addressFinder(p[3]);
memoryLink.addTooMemory(p[2],p[3],p[1]);
memoryLink.merge();
drumQueue.add(p);
Swap(a,0);
}

I think you class store data in proper way, but it have a problem in print() method. peek() always return head of the queue, so you just print first element size() times. Try to use queue.toArray() for printing purposes

Related

How would I create a method that stores the parameter value in an array at the index of the position variable, then adds 1 to the position variable

I have an assignment to create an array class where there are 2 constructors where each constructor sets a different size for the array.
The array is already an instance variable along with another instance variable to keep track of the current position in the array.
I have to create a method called add with an integer parameter that will store the parameter value in the array at the index of the position variable, then add 1 to the position variable. If the incremented position variable is outside the bounds of the array, the method calls the addspace method.
The addspace method creates a new array 25% larger than the instance variable array, copies all the values of the instance array to the new array, and assigns the new array to the instance variable.
I also need a method called size that will return the value in the position variable and a method called get that with 1 parameter(an index), the method returns the value at the parameter index.
The last thing I need is a print method that uses a for loop to print the values in the array.
So far this is what I have
public class ArrayClass
{
private int array[];
private int x=0;
public ArrayClass()
{
this.array= new int[10];
add(1);
getThat(0);
print();
}
public ArrayClass(int y)
{
this.array= new int[y];
add(2);
getThat(0);
print();
}
public void add(int a)
{
array[x]=a;
x++;
if(x>array.length)
addspace();
}
public void addspace()
{
double d=array.length+(array.length*0.25);
int v=(int)d;
int newArray[]= new int[v];
for(int i=0; i<array.length; i++)
{
newArray[i]=array[i];
System.out.println(newArray[i]);
}
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
for(int i=0; i<array.length; i++)
System.out.println(array[i]+" ");
}
public static void main(String[] args)
{
new ArrayClass();
new ArrayClass(5);
}
}
I know the title only asks for help with the first method but if someone would be kind enough to help with the other methods and the reason why my code won't run and print what I want it to that would be much appreciated.
Use the ArrayClass for only for declaring your functionality.Call add method as obj.add(number) until and unless you need to add something inside ArrayClass constructor itself.
Modified these things as per my understanding
In your add method you are assigning the value first and then adding space if the array is full, in this case, you are increasing the size even if it might not be needed (i.e not calling add method again).
Instead of this increase the size only when you require it.
In print function you are iterating through the whole array.Modified to-> it will iterate till the last index of value (i.e x)
package com.example;
public class ArrayClass
{
private int array[];
private int x=0;
private final int DEFAULT_SIZE=4;
public ArrayClass(){
this.array = new int[DEFAULT_SIZE];
}
public ArrayClass(int size){
this.array = new int[size];
}
public void add(int number){
//check whether array have space or not .if not then increase the space.
if(x > this.array.length-1){
addSpace();
}
array[x] =number;
x++;
}
private void addSpace(){
double newSize = array.length + array.length * 0.25;
int tempArray[] = new int[(int) newSize];
for(int i=0; i<array.length; i++){
tempArray[i]=array[i];
}
this.array = tempArray;
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
//instead of of printing the whole array Printed till last value index.
for(int i=0; i<x; i++)
System.out.println(array[i]+" ");
}
}
From the main method
ArrayClass ac1 = new ArrayClass();
ac1.add(5);
ac1.add(4);
ac1.add(5);
ac1.add(4);
ac1.add(7);
ac1.add(19);
ac1.print();
ArrayClass ac2 = new ArrayClass(5);
ac2.add(1);
//rest of your function call here

Method adding element to array of ints

I need help with creating a method that adds input int to an array, and returning a message if array is already full.
I have class Lista with 3 fields numbers, capacity and size. Than I have a counstructor taking int as parameter and seting the capacity of array for the object of Lista class. So far i have this code:
public class Lista {
private int[] numbers;
private int capacity;
private int size;
public Lista (int capacity) {
this.size = 0;
this.capacity = capacity;
this.numbers = new int[capacity];
}
public void addElement(int element) {
}
public static void main(String[] args) {
Lista lista = new Lista(10);
lista.addElement(1);
lista.addElement(2);
lista.addElement(3);
System.out.println(lista.numbers[1]);
I've tried with loops and ArrayLIst but nothing i wrotr realy worked. WHat would be the best way to do it?
You could implement your addElement method like so:
public void addElement(int element) {
if(size == capacity) {
System.out.println("array is full");
return;
}
numbers[size++] = element;
}
You need to throw exception when list is already full and you try to insert next element to it:
class List {
private int[] numbers;
private int nextIndex;
public List(int capacity) {
this.numbers = new int[capacity];
}
public void addElement(int element) {
if (nextIndex < numbers.length) {
numbers[nextIndex] = element;
nextIndex++;
} else {
throw new RuntimeException("list is full");
}
}
public int capacity() {
return numbers.length;
}
public int size() {
return nextIndex;
}
}
I've tried with loops and ArrayLIst but nothing i wrotr realy worked.
WHat would be the best way to do it?
You use an array to store your values, so you don't need to use ArrayList (it is an alternative).
A loop is for iterating. You don't need it either.
I need help with creating a method that adds input int to an array,
and returning a message if array is already full.
Returning a textual message is not really the way which an API should be designed. It should rather returns a boolean to indicate the result of the invocation.
For example, look at the boolean add(E e) method of the Collection interface.
So, you should change the declaration of addElement() in order to return a boolean to indicate if the element was added or not (the last one when the max capcacity was reached).
public boolean addElement(int element) {
if(size == capacity) {
return false;
}
numbers[size++] = element;
return true;
}
If you want to output a textual message, you could test the value of the boolean :
if (!myLista.addElement(5)){
System.out.println("max capacity added. Cannot add the element");
}

Inserting into a simple Array and Deleting

public class DataOperations {
int arraySize=50;
int[]array=new int[arraySize];
public void generateRandomArray(){
for(int i=0;i<arraySize;i++){
array[i]=i;
}
}
public int getValueAtIndex(int index){
if(index<arraySize){
System.out.println("Your value At index "+index+" is "+array[index]);
return array[index];
}else{
System.out.println("Please Return an Index that is inbounds");
return 0;
}
}
public boolean doesArrayContainValue(int searchValue){
boolean valueInArray=false;
for(int i=0;i<arraySize;i++){
if(array[i]==searchValue){
valueInArray=true;
}
}
return valueInArray;
}
public void deleteIndex(int index){
if(index<arraySize){
for(int i=index;i<(arraySize-1);i++){
array[i]=array[i+1];
}
}
System.out.println(arraySize);
arraySize--;
System.out.println(arraySize);
}
public void printArray(){
for(int i=0;i<arraySize;i++){
System.out.print(i+"-");
System.out.println(array[i]);
}
}
public void insertValue(int index){
if(index<arraySize){
array[arraySize]=index;
System.out.println(arraySize);
arraySize++;
System.out.println(arraySize);
}
}
public void linearSearchForValue(int value){
boolean valueInArray=false;
System.out.println("The was Found and is at Index:");
for(int i=0;i<arraySize;i++){
if(array[i]==value){
System.out.println(i);
}
}
}
}
Hey So I created simple add and delete methods to my array. However, I am unsure about a couple parts. I Understand the add method, and that we are decreasing the arraySize from 50 to 49 for this specific array object that I created in my Driver class below. However, I am not sure why I cannot do my add method before my delete method insertValue method if I put arraySize++ before array[arraySize]=index, and did not call my deleteIndex method shouldnt my arraySize=51? but this throws an out of bounds exception
Driver Class Below
public class Driver {
public static void main(String[] args) {
DataOperations array=new DataOperations();
array.generateRandomArray();
array.insertValue(20);
array.printArray();
}
}
int arraySize=50;
You create an array of size 50. Arrays are of fixed size hence you cannot get an array of size 51. In your code, when adding/deleting an element from the array, you arent changing the size of the array. You are just moving the index to get your desired output. If you want a bigger array you can:
Create a new array of required size and copy all elements from old to new
Use ArrayList instead of arrays.

Generic array index out of bounds

Ok , here is my problem . I'm learing to use generic classes and methods. I want to make an generic array list and method that will add/remove element by choosen index. I simply doesn't know how to do that . My example is calling an IndexOutOfBoundsException.
Any help is welcome.
Thanks it advance .
class klasa3:
public class klasa3<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
public klasa3(int initSize){
}
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o,int indeks) {
o = list.get(indeks);
list.add(o);
}
public E pop(int indeks) {
E o = list.get(indeks);
list.remove(indeks);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public String toString() {
return "stack: " + list.toString();
}
}
main class:
public class klasa2 {
public static void main(String[] args ) {
klasa3 stak2 = new klasa3(13);
stak2.push("cola",2); // problem here
stak2.pop(2);
System.out.println(stak2.getSize());
}
}
You're creating an empty ArrayList, and then trying to get the third element (element at index 2) from it within your push method. That's not going to work.
Now, you're currently ignoring your initSize parameter in your constructor. You might want something like:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize) {
for (int i = 0; i < initSize; i++) {
list.add(null);
}
}
Or provide a default element:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize, E element) {
for (int i = 0; i < initSize; i++) {
list.add(element);
}
}
This is what is happening:
In the main method you first create a new klasa3 object. Then you call push("cola", 2) on it.
The push method does: o = list.get(indeks), where indeks is 2. At this point the list is empty, so 2 is not a valid index, which causes an IndexOutOfBoundsException.
The index that you pass to the get method must be between 0 (inclusive) and the size of the list (exclusive). Since the size is 0, the index 2 is invalid.

How to add an Object to a Generic array using a method Java

I want to add an object to my array. I am trying to create a method so whenever it's called, it adds the generic type object. Here's my code:
public class ArrayObjects<E> implements SomeImp<E>{
private E[] list;
private int maxCapacity, currentSize;
public ArrayObjects(){
maxCapacity = 10;
array = (E[]) new Object[maxCapacity];
}
public void addObj(E obj){
array.add(obj); //Throws an error
}
}
Eclipse shows me an error though. It says "Cannot invoke add(E) on the array type E[ ]"
Does anyone know why does this happen? Do you know of an alternative of adding an object to my generic array?
Thank you!
EDIT:
When I create an instance of a class that instantiates ArrayObjects, and try to add a value to it, it doesn't do it. code:
import packageWhereArrayObjectsIs.*;
public class Test {
private ArrayObjects<Integer> list;
public Test() {
list = new ArrayObjects<Integer>();
Test();
}
private void TestOne() {
for(int i=1; i <= 10; i++)
list.addLast(i);
System.out.println("Should print 1 .. 10");
System.out.println(list);
}
}
The method add() does not exist for arrays. You must access array elements using the correct syntax []:
public void addLast(E obj) {
array[currentSize++] = obj;
}
In order for your list to print nicely, you'll want to add a toString() method to your ArrayObjects class:
public String toString() {
return Arrays.toString(array);
}
To iterate over the elements of your ArrayObjects, you can implement the Iterable interface:
public class ArrayObjects<E> implements Iterable<E>
This requires your class to have an iterator() method that returns an Iterator:
public Iterator<E> iterator() {
class It implements Iterator<E>
{
int position = -1;
public boolean hasNext() {
return position + 1 < currentSize;
}
public E next() {
return array[++position];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
return new It();
}
Finally, this code shows how you can now iterate over your list using an enhanced for loop:
ArrayObjects<Integer> list = new ArrayObjects<Integer>();
for (int i = 0; i < 10; i++) list.addLast(i);
for (Integer i: list) {
System.out.println("Iterating over list! Next element is " + i);
}
You should do something like this, assuming that your actual size is 1 when you add your first element BUT the position will be 0 because it's the first position of the array.
public boolean addObj(E obj){
if(actualSize == maxCapacity){
return false;
}
array[actualSize--] = obj;
return true;
}
I changed the return value to return false if there is no positions left in the array (considering that you won't remove any object in the middle).
Why do you need an array? Why not going with a List?
public class ArrayObjects<E> implements SomeImp<E>{
private List<E> list;
private int maxCapacity;
public ArrayObjects(){
maxCapacity = 10;
list = new ArrayList<E>();
}
public boolean addObj(E obj){
if(list.size() == maxCapacity){
return false;
}
list.add(obj);
return true;
}
}
See that using a List you won't have to deal with the actualSize.
EDIT: as Smac89 points out, it makes no sense to use a list. But keep in mind you will have to find an empty position if the array is not full.

Categories