简体   繁体   中英

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.

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.

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

As per docs

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

In that way get() method added

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM