Results 1 to 3 of 3
  1. #1
    blug is offline Member
    Join Date
    Oct 2010
    Posts
    26
    Rep Power
    0

    Default Array null values

    Hi, I'm having a bit of a problem with this code. I've looked over it a few times and I just can't see it being illogical? It makes sense to me and should be working.

    PHP Code:
    public void add(Object object){
    		sizeArray++;
    		Object[] temp = new Object[sizeArray];
    		this.array = temp;
    		this.array = new Object[sizeArray + 1];
    		for(int i = 0; i < temp.length; i++){
    			array[i] = temp[i];
    		}
    		array[sizeArray] = object;
    	}
    I'm trying to do a remake of the "ArrayList" as what my textbook is asking me to do. However, this code here is returning nothing but null values besides the last the last element of the array which returns correctly (which makes sense to me).

    Am I doing something wrong with the array/temp coversion?

    Thanks!!

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    i think this is the problem:

    - a new array 'temp' is initialized (it has no values - so 'null')
    - class field 'array' = temp //essentially resetting the array with the new size
    - 'array' = new Object[sizeArray+1] // i don't understand
    - you iterate through the new NULL array and replace the items with temp array which is also NULL because neither new nor reset array have had values assigned to them
    - the latest item 'object' is added

    the method is clearly flawed in that it does not copy the values of the original array held in the class field 'array' to the new temp array

  3. #3
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    you might want to change this around:
    Java Code:
    this.array = temp; 
    this.array = new Object[sizeArray + 1];

    to something like this:
    Java Code:
    temp = array;
    array = new Object[sizeArray + 1];

    i think that should do it

Similar Threads

  1. Replies: 14
    Last Post: 01-22-2011, 02:36 PM
  2. Replies: 6
    Last Post: 10-18-2010, 10:40 AM
  3. cant print 2d array(giving null values)
    By fneeks in forum New To Java
    Replies: 1
    Last Post: 04-07-2010, 08:48 PM
  4. null values
    By jabo in forum New To Java
    Replies: 3
    Last Post: 03-31-2010, 03:44 PM
  5. How to get null values stored in array
    By Ms.Ranjan in forum New To Java
    Replies: 4
    Last Post: 05-21-2009, 10:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •