File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes dynamic array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "dynamic array" Watch "dynamic array" New topic

dynamic array

Arjun Shastry
Ranch Hand

Joined: Mar 13, 2003
Posts: 1893
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

Joined: Mar 07, 2007
Posts: 1294


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".

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
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

Joined: Jul 11, 2001
Posts: 14112
Do you really need to *enforce* that there won't be more than 10 numbers?

Otherwise, why not just use an array?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
abu alfouz
Ranch Hand

Joined: Nov 20, 2006
Posts: 44
Why you don't use a list contains wrapper class "java.lang.Integer"?

SCJP 1.5
I agree. Here's the link:
subject: dynamic array
It's not a secret anymore!