How can I insert an element into a List?

Brandon Rohlfs

In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index > size() an exception will be thrown.

import java.util.*; 

public class Insert{
 public static void main(String[] args){
  List<String> slist = new ArrayList<String>();
  slist.add(new String("Java")); 
  slist.add(new String("Write")); 
  slist.add(new String("run"));
  slist.add(new String("anywhere!")); 
  slist.add(2,new String("once"));
  for(String s:slist){
   System.out.println(s); 
  }
 }
}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact