Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Add an object to Array of Objects

 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ryan Sykes
Ranch Hand
Posts: 58
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it! Thanks so much guys I'll get to work!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic