reordering an arraylist
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Monday, November 28, 2005 03:26 AM

How to reorder an arraylist i.e i have an arraylist containing 5 elements.I have
to pass the start index(i.e which element to replace) and end index(where to replace) and
these indexes can repeat more than once.These indexes are passed from command line like
java classname startindex1 endindex1 startindex2 endindex2.the remaining elements
should move down after replacing.how to do this.can u send a sample program for this.

Re: reordering an arraylist

Posted By:   Anonymous  
Posted On:   Saturday, December 3, 2005 07:03 AM

If I got your question right here is solution

try it out

package collection;



import java.util.ArrayList;



public class CollectionTest {



public static void main(String[] args) {



try {



ArrayList oArrayList = new ArrayList();


// Populate the data for application


oArrayList.add("A");oArrayList.add("B");oArrayList.add("C");oArrayList.add("D");oArrayList.add("E");



String strTemp = "";


int iStartIndex = 0;


int iEndIndex = 0;


System.out.println(" : Data --> " + oArrayList.toString());



if(args.length %2 == 0) {


System.out.println("
Valid argument list");


for(int i = 0; i<= args.length/2; i=i+2) {



iStartIndex = Integer.parseInt(args[i]);


iEndIndex = Integer.parseInt(args[i+1]);


//check data is within arraylist else will give error


if(iStartIndex <= oArrayList.size() && iEndIndex <= oArrayList.size()) {


System.out.println("
Valid indexes let's do swapping");


strTemp = oArrayList.get(iStartIndex-1).toString();


oArrayList.remove(iStartIndex-1);


oArrayList.add(iEndIndex-1, strTemp);


System.out.println(" : " + iStartIndex + " moved to " + iEndIndex + " --> " + oArrayList.toString());


} else {


System.out.println("
Invalid index specified");


} // End of if loop


}// End of for loop


} else {


System.out.println("
InValid argument list");


} // End of if loop


} catch (Exception ex) {


System.out.println(" Exception occured at runtime : " + ex.getMessage());


}


} // End of main


}// End of class
About | Sitemap | Contact