• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Add an object to Array of Objects

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 58
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Got it! Thanks so much guys I'll get to work!
 
reply
    Bookmark Topic Watch Topic
  • New Topic