Quickly grasp the common use of ArrayList and Vector classes in the Java container

  • 2020-04-01 04:23:17
  • OfStack

ArrayList class
Instantiation of List collection:


List<String> l = new ArrayList<String>(); //The List collection is instantiated using the ArrayList class
List<String> l2 = new LinkedList<String>(); //Use the LinkedList class to instantiate the List collection

Common methods of ArrayList:

The add (int index, Object obj); AddAll (int, Collection coll); Remove (int index); Set (int index, Object obj); Get (int index); IndexOf (Object obj); The lastIndexOf (Object obj); ListIterator (); ListIterator (int index);

Example of ArrayList: an implementation that creates an empty ArrayList object, adds elements to it, and then outputs all elements.


<%@ page import="java.util.*" %>
<%
  List<String> list = new ArrayList<String>();
  for(int i=0;i<3;i++) {
    list.add(new String(" fuwa " + i));
  }
  list.add(1, " After adding fuwa ");
  //Output all elements
  Iterator<String> it = list.iterator();
  while(it.hasNext()) {
    out.println(it.next());
  }
%>

The output result is:


 fuwa 0  After adding fuwa   fuwa 1  fuwa 2 

The usage of the LinkedList class is similar to that of the ArrayList class.

The Vector class
Common methods of Vector class:

The add (int index, Object element); AddElementAt (Object obj, int index); The size (). ElementAt (int index); SetElementAt (Object obj, int index); RemoveElementAt (int index);

Instance of Vector class: implement creating an empty Vector object, adding elements to it, and then outputting all elements.


<%@ page import="java.util.*" %>
<%
  Vector v = new Vector(); //Create an empty Vector object
  for(int i=0;i<3;i++) {
    v.add(new String(" fuwa " + i));
  }
  v.remove(1); //Removes an element with an index position of 1
  //Display all elements
  for(int i=0;i<v.size();i++) {
    out.println(v.indexOf(v.elementAt(i))+": "+v.elementAt(i));
  }
%>

The display result is:


0:  fuwa 0 1:  fuwa 2 


Related articles: