wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Add an object to Array of Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Add an object to Array of Objects" Watch "Add an object to Array of Objects" New topic
Author

Add an object to Array of Objects

Matt Wilde
Ranch Hand

Joined: Feb 27, 2012
Posts: 34
So i have a class ElectronicDevice.
I have another class SurgeProtector.

In surge protector i have
ElectronicDevice[] ED = new ElectronicDevice[20];

In surge protector i have a method

public boolean addDevice (ElectronicDevice e){
return true; //return false if nothing added
}

in the addDevice method how do i add an ElectronicDevice e to the array ED?
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7032
    
  16

Matt Wilde wrote:in the addDevice method how do i add an ElectronicDevice e to the array ED?

You can't as it stands because you need to provide an index. Either that, or you need to keep a 'current index' to the array somewhere else.

Personally, I'd have a look at ArrayList. That, you can add to.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
Matt, you will probably want to have an int instance variable in SurgeProtector, like int lastIndex, that keeps track of the lastIndex of the elements inserted into the array. Use that index value to add an element to the array and then increment lastIndex by 1. I'd recommend looking at the ArrayList source code in Java. I always find it fun to see how things are implemented and you can learn quite a bit. ArrayList essentially consists of an internal array, that is dynamically resized (rather, duplicated) when the size of the ArrayList exceeds the initial size of the internal array representation.
Matt Wilde
Ranch Hand

Joined: Feb 27, 2012
Posts: 34
Got it! Thanks so much guys I'll get to work!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Add an object to Array of Objects
 
Similar Threads
Is there java class to parse xml nodes?
problem passing value to method in correct order(SOLVED)
I need help with my project! ADT
Doubt in K&B SCJP 5: topic Converting Arrays to Lists to Arrays
Dilemma to sort out