Java Programming - Objects and Collections - Discussion

3. 

Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized?

[A]. java.util.HashSet
[B]. java.util.LinkedHashSet
[C]. java.util.List
[D]. java.util.ArrayList

Answer: Option D

Explanation:

All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.


Jagan M Reddy said: (Aug 29, 2011)  
What about java.util.list, I think its correct but I think its interface. I have doubt over here please can u solve it for me ?

Omprakash said: (Jan 25, 2013)  
The current code will not compile due to the error introduced due to incorrect paranthesis.

The correct code would be,
java.io.PrintWriter out = new java.io.PrintWriter(new java.io.OutputStreamWriter(System.out), true);

PrintWriter accepts OutputStream and boolean as its arguments in one its constructor. The above code will ensure that the PrintWriter obj acts as System.out

Mac said: (May 10, 2015)  
@Jagan.

Yes, java.util.List is an interface and it is a subtype of the java.util.Collection interface.

Deepak said: (Nov 10, 2015)  
Methods are not synchronized?

But vector has synchronized, then how to it not synchronized?

Faruque said: (Nov 28, 2015)  
The java.util.ArrayList.get(int index) method returns the element at the specified position in this list.

Following is the declaration for java.util.ArrayList.get() method

public E get(int index)

For example:

import java.util.ArrayList;

public class ArrayListDemo {
public static void main(String[] args) {

// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

// use add() method to add elements in the list
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
System.out.println(arrlist);

// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}

// retrieves element at 4th postion
int retval=arrlist.get(3);
System.out.println("Retrieved element is = " + retval);
}
}

Output:

[15, 22, 30, 40].
Number = 1.
Number = 22.
Number = 30.
Number = 40.
Retrieved element is = 40.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.