Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between get(int index) and elementAt(int index)?

Vector has two methods to get the element at one index.

Vector<Integer> matrix;
matrix = new Vector<Integer>;
matrix.get(0);
matrix.elementAt(0);

It seems they are doing the same thing here.

like image 522
Johnny Chen Avatar asked Oct 21 '25 17:10

Johnny Chen


2 Answers

They both do the same job. You can visit the Javadoc of Vector#elementAt(int), that states it clearly:

This method is identical in functionality to the get(int) method (which is part of the List interface).

Well, you should not use Vector anymore in new code. It's legacy class, that was long back replaced by ArrayList. Moreover, every operation defined in Vector are synchronized, which is most of the time not needed. And whenever you need, you should use Collections.synchronizedList, instead.

And also you cannot create an array of parameterized type as you're doing in your code. So, your code won't even compile.

new Vector<Integer>[100];  // This will not compile. Error: Generic Array Creation
like image 67
Rohit Jain Avatar answered Oct 24 '25 09:10

Rohit Jain


The difference is that Vector like Hashtable and Stack are legacy classes which were redesigned in Java 1.2 in 1998 to be replaced with ArrayList.

elementAt(int) is the legacy method

get(int) complies with the List interface added 15 years ago now.

In short, don't use Vector unless you really have to.

like image 45
Peter Lawrey Avatar answered Oct 24 '25 09:10

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!