在arraylist java

时间:2016-03-15 12:26:34

标签: java algorithm logic

我有以下数组列表:

arrList = {"A", "2b", "3c", "4x", "5y", "6k", "7", "8", "9", "10", "11", "13", "14", "15", "16", "17", "18", "19", "20"}

我希望将这些元素移动到所以它变成:

arrList = {"A", "3c", "4x", "5y", "6k", "2b", "7", "8", "9", "10", "11", "13", "14", "15", "16", "12", "17", "18", "19", "20"}

注意以下项目: 第二位置已移至第六位。 第12位已移至第16位

任何人都可以告诉我如何使用for循环实现这一目标吗?还是有更好的方法?

如果我的列表是动态的并且不断增长,我希望继续使用相同的模式,以便项目位于:

第22位将移至第26位

7 个答案:

答案 0 :(得分:4)

就代码行而言,最简单的方法是从列表中删除元素并将其重新插入新位置:

list.add(toPos, list.remove(fromPos));

但是,这并不是最有效的方法,因为它要求数组列表中的所有元素都被删除向下移动,并通过插入向上移动。

通过明确地将所有元素移位到位,可以更有效地完成它:

Integer fromValue = list.get(fromPos);
int delta = fromPos < toPos ? 1 : -1;
for (int i = fromPos; i != toPos; i += delta) {
  list.set(i, list.get(i + delta));
}
list.set(toPos, fromValue);

答案 1 :(得分:3)

简单示例如何将一个元素移动到另一个元素而不会丢失数据。

public void move(List myList, int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            myList.add(toPosition, myList.get(fromPosition));
            myList.remove(fromPosition);
        } else {
            myList.add(toPosition, myList.get(fromPosition));
            myList.remove(fromPosition + 1);
        }
    }

对于:[A][B][C][D][E]


案例1 :将[A]->[B]从第0位移至第1位,条件为fromPosition < toPosition
第1步:[A][A*][B][C][D][A]移至第二位(param toPosition)
第2步:[A*][B][C][D]删除旧的[A]位置(param fromPosition)


案例2 :将[C]->[A]从第2位移至第0位,条件为fromPosition >= toPosition
第1步:[C*][A][B][C][D][C]移动到第一个位置(param toPosition) - 我们向左移动,因此列表被剔除(旧的[C]位置增加+1)
第2步:[C*][A][B][D]删除旧的[C]位置(param fromPosition)

答案 2 :(得分:1)

由于您基本上将第二个元素移动到第六个位置等,您可以执行以下操作:

  • 移除第二个元素,从而将剩余的元素向左移动1个/ l
  • 在所需位置读取元素

这可以在一行中完成:list.add( targetPos, list.remove( sourcePos ) )

当然,通过手动操作仅仅移动必须移动的部分仍然效率不高,但除非你经常调用它或者拥有大量列表,否则你可能不想打扰它。

而且,正如已经指出的那样,你必须确保sourcePos < targetPos

答案 3 :(得分:0)

您的要求并不明确,但要在数组列表中移动元素,请使用 ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the <c>MP3GAIN_MINMAX</c> metatada field of the audio file. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <c>MP3GAIN_MINMAX</c> field value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Function GetFieldMP3GainMinMax() As String Dim data As Byte() = Encoding.UTF8.GetBytes("MP3GAIN_MINMAX") Dim vector As New ByteVector(data) Dim offset As Long = Me.mp3File.Find(vector) Dim result As String If (offset = -1) Then Return String.Empty Else Try offset += ("MP3GAIN_MINMAX".Length + 1) Me.mp3File.Seek(offset, SeekOrigin.Begin) result = Me.mp3File.ReadBlock(8).ToString.TrimEnd() Return result Catch ex As Exception Throw Finally Me.mp3File.Seek(0, SeekOrigin.Begin) End Try End If End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the <c>MP3GAIN_UNDO</c> metatada field of the audio file. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <c>MP3GAIN_UNDO</c> field value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Function GetFieldMP3GainUndo() As String Dim data As Byte() = Encoding.UTF8.GetBytes("MP3GAIN_UNDO") Dim vector As New ByteVector(data) Dim offset As Long = Me.mp3File.Find(vector) Dim result As String If (offset = -1) Then Return String.Empty Else Try offset += ("MP3GAIN_UNDO".Length + 1) Me.mp3File.Seek(offset, SeekOrigin.Begin) result = Me.mp3File.ReadBlock(12).ToString.TrimEnd() Return result Catch ex As Exception Throw Finally Me.mp3File.Seek(0, SeekOrigin.Begin) End Try End If End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the <c>REPLAYGAIN_TRACK_GAIN</c> metatada field of the audio file. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <c>REPLAYGAIN_TRACK_GAIN</c> field value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Function GetFieldReplayGainTrackGain() As String Dim data As Byte() = Encoding.UTF8.GetBytes("REPLAYGAIN_TRACK_GAIN") Dim vector As New ByteVector(data) Dim offset As Long = Me.mp3File.Find(vector) Dim result As String If (offset = -1) Then Return String.Empty Else Try offset += ("REPLAYGAIN_TRACK_GAIN".Length + 1) Me.mp3File.Seek(offset, SeekOrigin.Begin) result = Me.mp3File.ReadBlock(12).ToString.TrimEnd() Return result Catch ex As Exception Throw Finally Me.mp3File.Seek(0, SeekOrigin.Begin) End Try End If End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the <c>REPLAYGAIN_TRACK_PEAK</c> metatada field of the audio file. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <c>REPLAYGAIN_TRACK_PEAK</c> field value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Function GetFieldReplayGainTrackPeak() As String Dim data As Byte() = Encoding.UTF8.GetBytes("REPLAYGAIN_TRACK_PEAK") Dim vector As New ByteVector(data) Dim offset As Long = Me.mp3File.Find(vector) Dim result As String If (offset = -1) Then Return String.Empty Else Try offset += ("REPLAYGAIN_TRACK_PEAK".Length + 1) Me.mp3File.Seek(offset, SeekOrigin.Begin) result = Me.mp3File.ReadBlock(8).ToString.TrimEnd() Return result Catch ex As Exception Throw Finally Me.mp3File.Seek(0, SeekOrigin.Begin) End Try End If End Function 例如

答案 4 :(得分:0)

您可以使用方法subListaddAll

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#subList-int-int- https://docs.oracle.com/javase/8/docs/api/java/util/List.html#addAll-java.util.Collection-

例如

ArrayList myNewList = new ArrayList(); myNewList.addAll(sourceList.subList(2, 8)); myNewList.addAll(sourceList.subList(0, 1));

答案 5 :(得分:0)

你可以这样做(完全考虑你的要求):

int shiftCount = 4;

if(arrList != null) {
    for (int i = 1; i < arrList.size(); i +=10) {
        if(arrList.size() < i+shiftCount+1) break;
        String tmpObj = arrList.get(i);
        arrList.remove(i);
        arrList.add(i+shiftCount, tmpObj);
    }
}

答案 6 :(得分:0)

你的代码显示每个元素应该向右移动4个块我刚刚放置了最后4个元素,这样每个元素按照请求移动4个位置是我的代码

    String  arrList[] = {"A", "2b", "3c", "4x", "5y", "6k", "7", "8", "9", "10", "11", "13", "14", "15", "16", "17", "18", "19", "20"}; 
     String part1[] = new String[arrList.length-4];
     System.arraycopy(arrList, 0, part1,0, arrList.length-4);
     //System.out.println(arrList.length);
     String part2[] = new String[4];       
      System.arraycopy(arrList, arrList.length-4, part2,0, 4);
      System.out.println();
      String[] result = Stream.concat(Arrays.stream(part2), Arrays.stream(part1))
              .toArray(String[]::new);
      System.out.println();
      for(int hj =0 ;hj<result.length;hj++)
      { 
        System.out.print(result[hj]+" ");  
      }

希望您发现我的代码有用。