doubling Array size if full - java

I have an array of objects. When the array fills up, I want to make a new array twice as large as the old one, and transfer all the elements over. I'm doing something wrong, I think its something to do with I'm not creating the correct reference to the new array. Here's my code, any help figuring this out would be appreciated.
private int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
private int numberOfElements = 0;
public int getNumOfElements(){
return numberOfElements;
}
public void setDirectorySize(int size){
DIRECTORY_SIZE = size;
}
public int getDirectorySize(){
return DIRECTORY_SIZE;
}
public void addEntry(String surname, String initial, String num) {
// TODO add an entry to an array, also increments numberOfElements variable tracking whats in array
if(getNumOfElements() == getDirectorySize()){ // if array is full
doubleArraySize(); // put temp values into new bigger directory array
}
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
numberOfElements++;
}
private void doubleArraySize(){
Entry[] temp = new Entry[DIRECTORY_SIZE]; //make new temp array same size as old one
for(int i = 0; i < DIRECTORY_SIZE ; i++){
temp[i] = directory[i]; // cycle through array putting all values into temp
// works up to here
}
setDirectorySize(DIRECTORY_SIZE*2); // double size of array
Entry[] directory = new Entry[DIRECTORY_SIZE]; // create new, double size directory array
for(int i = 0; i < temp.length ; i++){
directory[i] = temp[i];
}
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}

In doubleArraySize() function , this is the issue :
Entry[] directory = new Entry[DIRECTORY_SIZE];
// you are not assigning it to the class attribute directory
// instead you are creating a local array directory
Make the following change :
this.directory = new Entry[DIRECTORY_SIZE];
// this will assign the newly created array to the class attribute
Note : I personally prefer to use this pointer to refer to class attributes so that it makes my code more readable, and its clear to everyone that the variable in question is a class attribute rather than local variable.
**SIZE has already double by this point. No need to multiple by 2

I remember doing something exactly like this when I was making a Vector ADT. However, I used instance variables instead of methods in my code for element number and the capacity. I definitely didn't initialize a Vector inside a method for a Vector.
setDirectorySize(DIRECTORY_SIZE*2); // double size of array
Entry[] directory = new Entry[DIRECTORY_SIZE]; // create new, double size directory array
Isn't DIRECTORY_SIZE an instance variable? Because if it is, I don't think you can initialize an object using an instance variable from the object you are overwriting.
Putting my code into your context, it would look something like this:
private void doubleDirectorySize()
{
Entry[] new_array = new Entry[new_directory_size*2];
for (int i = 0; i < directory_size; i++)
{
new_array[i]= directory[i];
}
directory= new_array;
}
This only works if directory was initialized to null, though, moving the pointer directory to the new array.

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

How to creart an ArrayList from array?

I am trying to create an ArrayList from a given array. This is the array I have:
public class Warehouse
{
private final static int MAX = 60;
private Item [] stock;
private int numItems;
public Warehouse()
{
stock = new Item[MAX];
numItems = loadData();
}
Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.
Why not use this?
List<Item> stockList = Arrays.asList(stock);
Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.
public class ArrayaData {
public int Id;}
And the within the next class,
public class ClassYouWant {
ArrayList<ArrayaData> arrayList ;
}
and when ever you want to add a value to that array just create a new instance and then save it.
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."
Or you can simply set it in a Loop as well,
int arraySize = 5; //Size of the array you want
for (int i = 0; i < arraySize; i++) {
arrayList = new ArrayList<ArrayData>();
arrayList.Id = "Value you want";
}
And to get the vlaues you can use a Loop also,
int arraySize = arrayList.size(); //Size of the created arrayList
int value;
for (int i = 0; i < arraySize; i++) {
value = arrayList.get(i);
Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();
}
Hope this helps..

Java: How to use functions of a class which has been instantiated by ArrayList

Here is just a simple example. Obviously there are simpler ways to set everything up within the constructor, but the arrayList I'm actually working with has already been set up, I just need to change individual sections of it. There HAS to be a way to call a class's functions in ArrayList, but for the life of me I can't figure out how.
import java.util.ArrayList;
public class ArrayTest{
public static void main(String[] args){
//Here's an example of a regular array:
Length[] lArray = new Length[3];
for (int i = 0; i < 3; i++){
lArray[i].setLength(i + 1);
}
//Here's how I was hoping ArrayList would function:
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
lList[i].setLength(i + 1);
// --OR--
lList.setLength(i, i + 1);
}
}
}
Here's the length class:
public class Length{
private int length;
Length(){
length = 0;
}
Length(int s){
length = s;
}
public void setLength(int s){
length = s;
}
}
Thanks!
You add elements to the ArrayList with add.
Since it's an ArrayList<Length>, you add Length objects:
lList.add(new Length());
And in your specific loop :
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
Length l = new Length();
l.setLength(i+1);
lList.add(l);
}
BTW, the array initialization is also missing an important initialization :
for (int i = 0; i < 3; i++){
lArray[i] = new Length(); // added
lArray[i].setLength(i + 1);
}
If the ArrayList already contains the elements, and you just want to modify them, you can write something like this:
lList.get(i).setLength(i + 1);
assuming that the ArrayList contains the ith element.
You could create a method with your operation/algorithm like
public void foo(){
System.out.println("some algorithm!");
}
inside Length class. This will operate on each instance of Length class.
And for iterating, you can use
ArrayList<Length> lList = new ArrayList<Length>(3);
for (Length l : lList){
l.foo();
}
This will call everything you code inside foo.

Cannot find symbol in for loop

I am getting the error now that BookCollection.java:67: error: incompatible types
collection[lastElement++] = b;
Also am not sure if my constructor is set up correctly? The directions were:
Constructor:
Given a parameter specifying the limit on the collection size, an empty book collection is created using the given parameter. The parameter should not exceed the preset maximum size 200.
Am I initializing my variables correctly then? An answer below helped me change my code, but although I do not get errors within my constructor, I feel as though it may not be correct according to the directions....
I'll paste the couple chunks of my code that pertain to the question.
public class BookCollection{
//data fields, need complete
private int limit = 200;
//Array of type book
private int Book[];
//actual size of collection, initialized to zero. Must never exceed limit
private int collection[];
private int lastElement;
//Constructor
public BookCollection(int l, int c[], int le,int b[]){
Book = b;
collection = c;
limit = l;
lastElement = le;
int lastElement = 0;
if(limit <= 200){
Book[] collection = new Book[limit];
} else{
throw new UnsupportedOperationException("CannotExceedLimit");
}
}
ANNDDDD where I am getting the error:
public void addBook(int b[], int c[]) {
Book = b;
collection = c;
if (lastElement == collection.length) {
throw new UnsupportedOperationException("CorrectionFull");
}
for (int i = 0 ; i != lastElement ; i++) {
if(b.equals(collection[i])) {
throw new UnsupportedOperationException("DuplicateBook");
}
}
collection[lastElement++] = b;
}
You have not declared i as an integer in your for loop. So add the declaration with initialization. Replace this
for(i=0; i<collection.length; i++){
with
for(int i=0; i<collection.length; i++){
This statement
BookCollection[] collection = new BookCollection[limit]; //initialize array of 200
declares a local array. It gets destroyed as soon as you leave the constructor.
The collection that stays around is this one:
private int collection[];
It consists of ints, so when you try to do this
collection[i].add(b);
the compiler correctly complains that int does not have a method called add.
Good chances are, even declaring the collection as
private Book[] collection;
and initializing it in the constructor as
collection = new Book[limit];
is not going to help, though: unlike collections, Java arrays do not let you change their size dynamically, so you need to store an index of the last element of the collection[] array that has been set.
This leads to understanding that you need a loop for finding duplicates, and noting else: define an element int lastElement, set it to zero in the constructor, and rewrite the addBook method as follows:
public void addBook(Book b) {
if (lastElement == collection.length) {
throw new UnsupportedOperationException("CorrectionFull");
}
for (int i = 0 ; i != lastElement ; i++) {
if(b.equals(collection[i])) {
throw new UnsupportedOperationException("DuplicateBook");
}
}
collection[lastElement++] = b;
}
You did't declared i as a int type variable, make it as
for(int i=0; i<collection.length; i++){
^here
//...
}

Java - How to declare table[i][j] elements as instance variables?

All,
I am trying to code a Connect4 game. For this, I have created a P4Game class and a P4Board class which represents the i X j dimensions of the Connect4 board.
In P4Game, I have the following:
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Game(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
P4Board [][] position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
for (int i=0; i<nbLines; i++){
for (int j=0; j<nbColumns; j++){
this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
}
}
}
This causes a NullPointerException in the nested loops where I mention this.position[i][j]. I reference those objects in other methods of this class so I need them to be instance variables. I suppose the exception is due to the fact that I have not listed the table element position[i][j] as an instance variable at the beginning of the class.
my question to people here is (1) is my assumption correct, and if so (2) what would be the syntax to declare instance variables of this form?
Thank you all for your help with what I realize is a very basic question. Hopefully it will also benefit other newbies.
Cheers,
JDelage
See added comment inlined... You code is fine except for one little detail, where you're creating a new position variable where you actually mean to use the instance variable.
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Jeu(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
// You're creating a LOCAL variable called position here if you don't comment what's commented:.
/*P4Board [][] */position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
for (int i=0; i<nbLines; i++){
for (int j=0; j<nbColumns; j++){
this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
}
}
}
}
Your assumption is incorrect.
In the constructor, you're making a local variable with the same name as the field. (By writing P4Board [][] position = ...) This creates a local variable and does not affect the field, which remains uninitialized. You need to remove the P4Board [][] to change it from a variable declaration to an assignment of the existing field. (Just like you write this.nbLines = ... to assign the field)
You're redefining P4Board [][] position in the constructor and then calling this.position which is not initialized (i.e. null).
Look out carefully! You are hiding the instance variable > P4Board [][] position = new P4Board [nbLines][nbColumns];
As others have said you are hiding the instance variable with a local variable. You should really check out checsktyle as it has checks to tell you if you have made such a mistake. Two other tools are PMD and FindBugs.
Your assumption is incorrect. Try looking a few lines higher for the bug in your homework.
This runs for me. I substituted into for P4Board, since you didn't supply it:
public class P4Game
{
private int nbLines;
private int nbColumns;
private int [][] position;
public static void main(String[] args)
{
P4Game game = new P4Game(3, 3);
System.out.println(game);
}
public P4Game(int nbLines, int nbColumns)
{
this.nbColumns = nbColumns;
this.nbLines = nbLines;
this.position = new int[this.nbLines][this.nbColumns];
for (int i=0; i < this.nbLines; i++)
{
for (int j=0; j < this.nbColumns; j++)
{
this.position[i][j] = i+j;
}
}
}
public String toString()
{
StringBuilder builder = new StringBuilder(1024);
builder.append('[');
for (int i = 0; i < this.nbLines; ++i)
{
builder.append('{');
for (int j = 0; j < this.nbColumns; ++j)
{
builder.append(this.position[i][j]).append(',');
}
builder.append('}');
}
builder.append(']');
return builder.toString();
}
}

Categories