• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dynamic array

 
Arjun Shastry
Ranch Hand
Posts: 1898
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to write a method which accepts variable number of elements.Method will do some work and return again variable number of elements.
I can use List/ArrayList can be used but element is of type integer.and there can be maximum of 10 numbers.Any other appraoch than using ArrayList?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Perhaps you could create your own container class as a wrapper around a List/ArrayList. There you could implement for example an add() method which constrains inserting of elements to a maximum number of 10.
And for type safety you could use a generic ArrayList<Integer> instead of a plain list. Or you could check at runtime with "instanceOf Integer".

Marco
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you know the type of variable and a maximum size in advance, try an array with the same size as the maximum, and a count variable. Whenever you add an element add it at [count++] and whenever you remove one you will have to move all the subsequent elements 1 back and decrement count by 1.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you really need to *enforce* that there won't be more than 10 numbers?

Otherwise, why not just use an array?
 
abu alfouz
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why you don't use a list contains wrapper class "java.lang.Integer"?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic