1

Say I instantiate 100 000 of Vectors

a[0..100k] = new Vector<Integer>();

If i do this

a[0..100k] = new Vector<Integer>(1);

Will they take less memory? That is ignoring whether they have stuff in them and the overhead of expanding them when there has to be more than 1 element.

4
  • I'm surprised the above code even compiles Commented Jul 3, 2010 at 19:46
  • That was just my attempt at pseudo-pseudo code. Commented Jul 3, 2010 at 22:07
  • 1
    Vector is so java1.2. use something current. Commented Jul 4, 2010 at 6:04
  • @seanizer Or so CLDC... Because there's nothing else unless you create it yourself. Commented Jul 4, 2010 at 12:41

5 Answers 5

8

According to the Javadoc, the default capacity for a vector is 10, so I would expect it to take more memory than a vector of capacity 1.

In practice, you should probably use an ArrayList unless you need to work with another API that requires vectors.

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, yes i was rather giving an example, but noted!
2

When you create a Vector, you either specify the size you want it to have at the start or leave some default value. But it should be noted that in any case everything stored in a Vector is just a bunch of references, which take really little place compared to the objects they are actually pointing at.

So yes, you will save place initially, but only by the amount which equals to the difference between the default size and the specified multiplied by the size of a reference variable. If you create a really large amount of vectors like in your case, initial size does matter.

Comments

2

Well, sort of yes. IIRC Vector initializes internally 16 elements by default which means that due to byte alignment and other stuff done by underlying VM you'll save a considerable amount of memory initially.

What are you trying to accomplish, though?

Comments

2

Yes, they will. Putting in reasonable "initial sizes" for collections is one of the first things I do when confronted with a need to radically improve memory consumption of my program.

Comments

1

Yes, it will. By default, Vector allocates space for 10 elements.

Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.increment is zero.

Therefore, it reserves memory for 10 memory references.

That being said, in real life situations, this is rarely a concern. If you are truly generating 100,000 Vectors, you need to rethink your designincrement is zero.

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.