Add an element to the end of an array (dynamic array)

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 2271 Views - Last Post: 14 October 2012 - 11:12 PM Rate Topic: -----

#1 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 06:09 PM

So I would try to ask again since my previous post has no response:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
 
class DynamicArrayOfInts 
{
 
    private int[] storage;
    private int size;
    private final  int INITIAL_CAPACITY = 8;
    private final int GROW_FACTOR = 2;
   
  
    public DynamicArrayOfInts() 
    {
      storage = new int[INITIAL_CAPACITY]; 
      size = 0;
    }
    
    //check for out of bound exception
    private void rangeCheck(int index)
    { 
    	if((index < 0)||(index == size)||(index > size))
    	{
      	  throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    	}
    	else
    	{
    		System.out.println("Array is inbound");
    	}
    }  
    
    //make sure array grow as there are more values to be added
    private void ensureCapacity(int size_wanted)
    {
      int max_capacity = storage.length;
      if (size_wanted > max_capacity) 
      {
        max_capacity = max_capacity * GROW_FACTOR +1; 
        storage = Arrays.copyOf(storage, max_capacity); // increases array size + copy contents
      } 
    }
    
    //get size of the array
    public int size() 
    {   
    	size = storage.length;
    	return size; // added so code would compile
    }
    
    //compare aThat array with the current array
	public boolean equals(Object aThat) 
	{ // aThat is a DynamicArrayOfInts object
		//check if aThat is empty or not instance of Dynamic
		if((aThat==null)||!(aThat instanceof DynamicArrayOfInts))
			return false;
		DynamicArrayOfInts aThatLocal = (DynamicArrayOfInts) aThat;
		//compare length
		if(storage.length != aThatLocal.size)
			return false;
		//compare elements
		for (int i = 0;i<storage.length;i++)
		{
			if(storage[i]!=aThatLocal.get(i))
			{
				return false;
			}			
		}
		return true;		
    } 
    
	//compare list with current array
    public boolean equals(List<Integer> list)  
    { // list is a LinkedList, or ArrayList, etc
    	//check size
    	if(list.size()!=storage.length)
    		return false; 
    	//compare elements
    	for (int i = 0;i<storage.length;i++)
    	{
    		if(storage[i] != list.get(i))
    		{
    			return false;
    		}
    	}
    	return true;
    	
    }
    
    //get value at the specific index
    public int get(int position)
    {
    	rangeCheck(position);    	
    	return storage[position];  
    }
    
    //set value at specific index
    public void set(int index, int value)
    {
    	rangeCheck(index);
    	storage[index]= value;    	
    }
    
    //insert value at specific index and shift everything from that index to the right
    public void insertAt(int index, int value) 
    {
    	if ((index<0)||(index>size))
    		throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    	else
    	{
    		int theLength = storage.length;
    		int temp=0;
    		int j=theLength;
    		ensureCapacity(size+1);
    		for(int i = (theLength-1);i != index;i--)
    		{
    			temp = storage[i];
    			storage[j] = temp;
    			j--;
    			
    		}
    		storage[index] = value;
    	}
    	
    }
    
    //add value to the end of array
    public void add(int value) 
    {	
    	int endPosition = size;
    	insertAt(endPosition, value);
    	
    }

    //remove 
    public void removeAt(int index) 
    {
    	rangeCheck(index);
    	if (index == 0 )
    	{
    		
    	}
    
    }
    
    //print everything out
    public void printAll() 
    {
    	for(int i = 0;i<storage.length;i++)
    	{
    		
    		System.out.print("[" + i + "]=" + storage[i] + "\t" );
    	}
    	System.out.println();
    }
    
    public static void main(String args[]) 
    {
       DynamicArrayOfInts list1 = new DynamicArrayOfInts();
       list1.insertAt(0,1);
       list1.insertAt(1,2);
       list1.add(3);
       // list1 is 1, 2, 3
       System.out.print("list1: "); list1.printAll();
       list1.set(2,100);
       // list1 1 is 1, 2, 100
       //System.out.print("list1: "); list1.printAll();
       System.out.println("list1[2]=" + list1.get(2));
       list1.removeAt(2);
       // list1 is 1, 2
       System.out.print("list1: "); list1.printAll();	 
       DynamicArrayOfInts list2 = new DynamicArrayOfInts();
       list2.insertAt(0,2);
       list2.insertAt(0,3);	 	
       list2.insertAt(0,1);
       list2.removeAt(1);
       // list2 is 1, 2
       System.out.print("list2: ");list2.printAll();
       System.out.println("list1.size()=" + list1.size() + ", list2.size()=" + list2.size());
       // list1 and list2 are equal
       System.out.println("list1 equals list2 is " + list1.equals(list2));
       list2.insertAt(2,3);
       // list2 is 1, 2, 3
       System.out.println("list1.size()=" + list1.size() + ", list2.size()=" + list2.size());	 	
       // list1 and list2 are not equal
       System.out.println("list1 equals list2 is " + list1.equals(list2));	
       ArrayList list3 = new ArrayList();
       list3.add(1);list3.add(2);list3.add(3);
       System.out.println("list2 equals list3 is " + list2.equals(list3));	       
    }    
} 



removeAt(index) I have not yet doing it... I want to finish add(value) first before move to that method. So basically the add method would add a value at the end of the array, by calling insertAt(index,value) but I am not sure how to accomplish that...

For removeAt(index) method, I think there are 2 different cases. One is when I remove in the middle or first index of the array; second is remove the last member in the array. For the first case, if i remove the values, I can shift everything after that index to the left. For the second case, I have to have some check to verify that I am removing the last member of the array, so I dont need to do the shifting, what can I do to check that?

Is This A Good Question/Topic? 0
  • +

Replies To: Add an element to the end of an array (dynamic array)

#2 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 06:16 PM

You can check if it's the last member of the array if the index is equal to the length of the array + 1(since arrays are 0 - index based and size is what you count them in the real world).
Was This Post Helpful? 1
  • +
  • -

#3 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 06:19 PM

How do I verify the last index of the array is indeed contain a value? U mean i should try and see if it == 0?
Was This Post Helpful? 0
  • +
  • -

#4 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 06:32 PM

Yep. Try it.
Was This Post Helpful? 0
  • +
  • -

#5 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 06:49 PM

wait a minute Sprawl, are we discussing the removeAt method? How should I do add(value) method?

This post has been edited by RozenKristal: 14 October 2012 - 06:49 PM

Was This Post Helpful? 0
  • +
  • -

#6 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:04 PM

Yes. Example:
storage ={1,2,3,4,5}
storage = removeAt(4,storage);

public static void int(int index, int[] originalArray){
 if(originalArray[index]==0){
   //remove that index
}
}



I've implemented it using System.arraycopy and here's a sample:

public class ArrayChecker {
	public static void main(String[] args) {
		int[] stuff = new int[10];
		System.out.println(stuff.length);
		stuff = removeAt(9,stuff);
		System.out.println(stuff.length);
	}
	
	public static int[] removeAt(int index, int[] array){
		if(array[index] == 0){
//Secret Array Manipulation Technique! :D/>
		}
		return null;
	}
}

Output:
10
9



Whoops, me returning null on that method is wrong, please ignore.
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:04 PM

removeAt() is easier to write
You create an array one slot less that the original one
You copy , but the element to remove, into the new one
You replace the old one by the new one
Was This Post Helpful? 1
  • +
  • -

#8 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:25 PM

View Postpbl, on 14 October 2012 - 07:04 PM, said:

removeAt() is easier to write
You create an array one slot less that the original one
You copy , but the element to remove, into the new one
You replace the old one by the new one


Oh... that way I dont need to shifting values around and check for last value in the array... I just need to remove that and copy over....
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:39 PM

just depends if your remove() method receiuces as parameter the index of the elemnt to remove or its value
Was This Post Helpful? 0
  • +
  • -

#10 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:42 PM

I only have removeAt(index) method, and no parameter that remove value.
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:45 PM

so it is really a piece of cake a 7-9 lines method :)
Was This Post Helpful? 1
  • +
  • -

#12 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:49 PM

View Postpbl, on 14 October 2012 - 07:45 PM, said:

so it is really a piece of cake a 7-9 lines method :)


I wish I have your brain, then my midterm tomorrow will be a piece of cake. :yes:
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 07:55 PM

Nothing to do with bvrain, it is just an exprerience issue
int[] arrayMinusOne(int[] orig, int exclude) {
   int[] tmp = new int[orig.length - 1];
   int idx = 0;
   for(int i = 0; i < orig.length; i++) {
       if(i == exclude)
          continue;
       tmp[idx++] = orig[i];
   }
   return tmp;
}


Was This Post Helpful? 2
  • +
  • -

#14 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 317
  • Joined: 29-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 08:07 PM

View Postpbl, on 14 October 2012 - 07:55 PM, said:

Nothing to do with bvrain, it is just an exprerience issue
int[] arrayMinusOne(int[] orig, int exclude) {
   int[] tmp = new int[orig.length - 1];
   int idx = 0;
   for(int i = 0; i < orig.length; i++) {
       if(i == exclude)
          continue;
       tmp[idx++] = orig[i];
   }
   return tmp;
}



I understood everything except this part:
if(i == exclude)
        continue


So when the index i = the removal index, skip that one and keep copying after that?
Was This Post Helpful? 0
  • +
  • -

#15 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Re: Add an element to the end of an array (dynamic array)

Posted 14 October 2012 - 08:58 PM

Deviating a bit from your question, I would like to tell you the difference between a break and a continue statement and also explain what is done by the continue in your program.

for(i=0;i<10;i++)
{
  if(i==5) break;
  cout<<i;
}



The output for the above will be 01234. The reason for that is break terminates execution of the nearest enclosing for statement.So, you will note that when 5 is encountered, the control comes out of the for loop.

Next, the continue.

for(i=0;i<10;i++)
{
  if(i==5) continue;
  cout<<i;
}



The output for the above will be 012346789. The reason for that is continue doesn't terminate execution but actually ignores the statement that comes after it(in this case, the printing of 5).
Therefore, you don't see 5 in your output.

Now,coming to your program, the statement following continue is the

tmp[idx++]=orig[i];


This particular statement will be ignored due to the continue.

regards,
Raghav

This post has been edited by raghav.naganathan: 14 October 2012 - 09:00 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2