java - Shifting in arrayList -


the method public static <t> arraylist<t> rotate(arraylist<t> al, int shift) accepts arraylist of string (at least in example) , shift indicated how arraylist should shift. if have, let's araylist of

[ a, b, c, d, e, f, g]  

and shift 2, method returns

[ f, a, b, c, d, e] 

or example,

[ a, b, c, d, e, f, g] 

and shift 4, method returns

[ d, e, f, g, a, b, c]  

i did method wrong , have no clue how approach problem. smb me ?

import java.util.arraylist; public class rotation{   // demonstrate rotat(a,shift) method   public static void main(string arg[]){     arraylist<character> charsl;     charsl = new arraylist<character>();     char [] chars = { 'a', 'b', 'c',                       'd', 'e', 'f'};     for(char c : chars){       charsl.add(c);     }     // charsl = [ a, b, c, d, e, f]      arraylist<character> result1;      result1 = rotate(charsl, 2);     // result1== [ e, f, a, b, c, d]     system.out.println(result1);      result1 = rotate(charsl, 7);     // result1== [ f, a, b, c, d, e]     system.out.println(result1);      // works srtings     arraylist<string> stringl;     stringl = new arraylist<string>();     string [] strs = { "a", "b", "c",                        "d", "e", "f", "g" };     for(string s : strs){       stringl.add(s);     }     // stringl = [ a, b, c, d, e, f, g]      arraylist<string> result2;      result2 = rotate(stringl, 7);     // result2== [ a, b, c, d, e, f, g]     system.out.println(result2);      result2 = rotate(stringl, 4);     // result2== [ d, e, f, g, a, b, c]     system.out.println(result2);   }    public static <t>   arraylist<t> rotate(arraylist<t> al, int shift){     // definition here         arraylist <t> newvalues = new arraylist<>();       arraylist <t> temp = new arraylist<>();        for(int = 0; < al.size(); i++)       {           newvalues.remove(al.get(shift));           newvalues.add(al.get(i));          //newvalues.add(shift, al.get(i));        }       return newvalues;    }  } 

try this:

public static <t> arraylist<t> rotate(arraylist<t> al, int shift) {     if (al.size() == 0)         return al;      t element = null;     for(int = 0; < shift; i++)     {         // remove last element, add front of arraylist         element = al.remove( al.size() - 1 );         al.add(0, element);     }      return al; } 

Popular posts from this blog