13

i've digging around about the same issue but i couldn't find the same as i had

i want to create an array without declaring the size because i don't know how it will be !

to clear the issue i'd like to give you the code that i'm looking up for

public class t
{
 private int x[];
 private int counter=0;
 public void add(int num)
 {
   this.x[this.counter] = num;
   this.counter++;
 }
}

as you see the user could use the add function to add element to the array 10000 times or only once so it's unknown size

2
  • 8
    java.util.ArrayList<E> Commented Aug 16, 2012 at 15:24
  • Yea, use ArrayList; it's like an array that can grow dynamically, you can get by index, put by index, put at end.... it's convenient. Commented Aug 16, 2012 at 15:28

6 Answers 6

13

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List<Float> unindexedVectors = new ArrayList<Float>();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);
Sign up to request clarification or add additional context in comments.

Comments

9

You might be looking for a List? Either LinkedList or ArrayList are good classes to take a look at. You can then call toArray() to get the list as an array.

Comments

3

As others have said, use ArrayList. Here's how:

public class t
{
 private List<Integer> x = new ArrayList<Integer>();

 public void add(int num)
 {
   this.x.add(num);
 }
}

As you can see, your add method just calls the ArrayList's add method. This is only useful if your variable is private (which it is).

2 Comments

What is the purpose of wrapping the ArrayList in another class?
If this is the entire class, then there is no purpose. But I wanted to show the OP how to use ArrayLists with his own code.
3

Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.

Comments

3

How about this

    private Object element[] = new Object[] {};

1 Comment

this basically says an array of size 0 . I doubt this would work.
1

I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.