在arrayList中移动 [英] Shifting in arrayList

查看:113
本文介绍了在arrayList中移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法 public static< T>ArrayList< T>rotation(ArrayList< T> aL,int shift)接受String的 Arraylist (至少在此示例中)和 shift 来指示arraylist的数量应该转变.如果有的话,让我们说一个

The method public static <T> ArrayList<T> rotate(ArrayList<T> aL, int shift) accepts an Arraylist of String (at least in this example) and a shift which indicated how much the arraylist should shift. If I have, let's say an arayList of

[ A, B, C, D, E, F, G] 

并且移位为 2 ,因此该方法返回

and the shift is 2, so the method returns

[ F, G, A, B, C, D, E]

或另一个示例

[ A, B, C, D, E, F, G]

shift 4 ,则该方法返回

[ D, E, F, G, A, B, C] 

我的方法完全错误,不知道如何解决此问题.smb可以帮我吗?

I did the method completely wrong and have no clue how to approach this problem. Could smb help me with that ?

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 WITH SRTINGS TOO
    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){
    // YOUR DEFINITION HERE 
      
      ArrayList <T> newValues = new ArrayList<>();
      ArrayList <T> temp = new ArrayList<>();
      
      for(int i = 0; i < aL.size(); i++)
      {
          newValues.remove(aL.get(shift));
          newValues.add(aL.get(i));
         //newValues.add(shift, aL.get(i));
          
      }
      return newValues;

  }

}

推荐答案

尝试一下:

public static <T> ArrayList<T> rotate(ArrayList<T> aL, int shift)
{
    if (aL.size() == 0)
        return aL;

    T element = null;
    for(int i = 0; i < shift; i++)
    {
        // remove last element, add it to front of the ArrayList
        element = aL.remove( aL.size() - 1 );
        aL.add(0, element);
    }

    return aL;
}

这篇关于在arrayList中移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆