Java Code Examples for java.util.Collections#swap()

The following examples show how to use java.util.Collections#swap() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public List<TbAddress> getAddressList(Long userId) {

    List<TbAddress> list=new ArrayList<>();
    TbAddressExample example=new TbAddressExample();
    TbAddressExample.Criteria criteria=example.createCriteria();
    criteria.andUserIdEqualTo(userId);
    list=tbAddressMapper.selectByExample(example);
    if(list==null){
        throw new XmallException("获取默认地址列表失败");
    }

    for(int i=0;i<list.size();i++){
        if(list.get(i).getIsDefault()){
            Collections.swap(list,0,i);
            break;
        }
    }

    return list;
}
 
Example 2
private void moveElement(int index, List<?> list) {
    int newIndex = 0;
    switch(this.getMovement()){
        case UP:
            newIndex = index - 1;
            if(newIndex >= 0 ){
                Collections.swap(list, index, newIndex);
            }
            break;
        case DOWN:
            newIndex = index + 1;
            if(newIndex < list.size()){
                Collections.swap(list, index, newIndex);
            }
            break;
    }
}
 
Example 3
Source Project: olat   File: PortfolioStructureDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void move(final PortfolioStructure structure, final AbstractArtefact artefact, final boolean up) {
    if (artefact == null || structure == null) {
        throw new NullPointerException();
    }
    if (structure instanceof EPStructureElement) {
        // save eventual changes
        dbInstance.updateObject(structure);
        // reconnect to the session
        final EPStructureElement structureEl = (EPStructureElement) dbInstance.loadObject((EPStructureElement) structure);
        final List<EPStructureToArtefactLink> artefactLinks = structureEl.getInternalArtefacts();
        final int index = indexOf(artefactLinks, artefact);
        if (up && index > 0) {
            // swap the link with the previous link in the list
            Collections.swap(artefactLinks, index, index - 1);
            dbInstance.updateObject(structureEl);
        } else if (!up && (index >= 0 && index < (artefactLinks.size() - 1))) {
            // swap the link with the next link in the list
            Collections.swap(artefactLinks, index, index + 1);
            dbInstance.updateObject(structureEl);
        }
    }
}
 
Example 4
Source Project: copybara   File: Command.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the reversal a command whose reversal has not been manually-specified.
 */
@Nullable
private static String reverse(String commandName, String args, Location location)
    throws EvalException {
  switch (commandName) {
    case "add":
      return "remove " + args;
    case "remove":
      if (args.contains(" ")) {
        // Do not reverse 'remove attr' operation. Only 'remove attr value'
        return "add " + args;
      }
      return null;
    case "replace":
      List<String> reverseArgs = new ArrayList<>(splitArgv(args));
      if (reverseArgs.size() != 3) {
        throw new EvalException(location,
            String.format("Cannot reverse '%s %s', expected three arguments, but found %d.",
                commandName, args, reverseArgs.size()));
      }
      Collections.swap(reverseArgs, 1, 2);
      return "replace " + Joiner.on(' ').join(reverseArgs);
  }
  return null;
}
 
Example 5
Source Project: opt4j   File: NeighborPermutationRevert.java    License: MIT License 6 votes vote down vote up
@Override
public void neighbor(PermutationGenotype<?> genotype) {
	int size = genotype.size();

	if (size > 1) {
		int a = random.nextInt(size - 1);
		int b;
		do {
			b = a + random.nextInt(size - a);
		} while (b == a);

		while (a < b) {
			Collections.swap(genotype, a, b);
			a++;
			b--;
		}
	}

}
 
Example 6
public void onReadStepMove(int fromPosition, int toPosition) {
    List<ReadStepItem> currentList = readStepItems.getValue();

    if (fromPosition >= currentList.size() || toPosition >= currentList.size()) {
        return;
    }

    List<ReadStepItem> newList = new ArrayList<>(currentList);
    Collections.swap(newList, fromPosition, toPosition);
    readStepItems.setValue(newList);
}
 
Example 7
void swap(int start, int end) {
  int localStart = getLocalPosition(start) - 1;
  int localEnd   = getLocalPosition(end) - 1;

  if (localStart < localEnd) {
    for (int i = localStart; i < localEnd; i++) {
      Collections.swap(records, i, i + 1);
    }
  } else {
    for (int i = localStart; i > localEnd; i--) {
      Collections.swap(records, i, i - 1);
    }
  }
}
 
Example 8
public void moveItemUp(View view, Language language) {
    int position = mLanguagesList.indexOf(language);
    if (position > 0) {
        Collections.swap(mLanguagesList, position, position - 1);
        view.startAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.button_click_scale));
        notifyItemRangeChanged(position - 1, 2);
    }
}
 
Example 9
@Override
public boolean onMove(int srcPosition, int targetPosition) {
    Collections.swap(books, srcPosition, targetPosition);
    notifyItemMoved(srcPosition, targetPosition);
    int start = srcPosition;
    int end = targetPosition;
    if (start > end) {
        start = targetPosition;
        end = srcPosition;
    }
    notifyItemRangeChanged(start, end - start + 1);
    return true;
}
 
Example 10
Source Project: ZZShow   File: NewsChannelAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    KLog.e("onItemMove","fromPosition="+fromPosition+"---toPosition="+toPosition);
    if(isChannelFixed(fromPosition,toPosition)) {
        return false;
    }
    Collections.swap(mList,fromPosition,toPosition);
    notifyItemMoved(fromPosition,toPosition);
    RxBus.getInstance().post(new ChannelItemMoveEvent(fromPosition,toPosition));
    return true;
}
 
Example 11
public static void main(String[] args) {

    //create a Vector object
    Vector v = new Vector();

    //Add elements to Vector
    v.add("1");
    v.add("2");
    v.add("3");
    v.add("4");
    v.add("5");

    System.out.println("Before swaping, Vector contains : " + v);

    /*
      To swap elements of Java Vector use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.
    */

    Collections.swap(v, 0, 4);

    System.out.println("After swaping, Vector contains : " + v);
  }
 
Example 12
Source Project: Nest4J   File: GeneticAlgorithmTest.java    License: MIT License 5 votes vote down vote up
@Test
public void swapTest() throws  Exception{
    List<Segment> s1 = new ArrayList<Segment>();
    s1.add(new Segment(1,2));
    s1.add(new Segment(3,4));
    Collections.swap(s1 , 0,1);
    for(Segment s : s1 ){
        System.out.println(s.getX()+" , "+ s.getY());
    }
}
 
Example 13
Source Project: brailleback   File: DeviceFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of bonded and supported devices in the order they
 * should be tried.
 */
public List<DeviceInfo> findDevices() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        return Collections.emptyList();
    }

    List<DeviceInfo> ret = new ArrayList<DeviceInfo>();
// getBondedDevices() may contain null.
Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
if (bondedDevices == null) {
  return ret;
}
    for (BluetoothDevice dev : bondedDevices) {
  if (dev == null) {
    continue;
  }
        for (SupportedDevice matcher : SUPPORTED_DEVICES) {
            DeviceInfo matched = matcher.match(dev);
            if (matched != null) {
                ret.add(matched);
            }
        }
    }
    String lastAddress = mSharedPreferences.getString(
        LAST_CONNECTED_DEVICE_KEY, null);
    if (lastAddress != null) {
        // If the last device that was successfully connected is
        // not already first in the list, put it there.
        // (Hence, the 1 below is intentional).
        for (int i = 1; i < ret.size(); ++i) {
            if (ret.get(i).getBluetoothDevice().getAddress().equals(
                    lastAddress)) {
                Collections.swap(ret, 0, i);
            }
        }
    }
    return ret;
}
 
Example 14
Source Project: MaterialHome   File: BookshelfFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            if (mBookshelfs.isEmpty()) {
                return false;
            }
            //得到拖动ViewHolder的position
            int fromPosition = viewHolder.getAdapterPosition();
            //得到目标ViewHolder的position
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                //分别把中间所有的item的位置重新交换
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(mBookshelfs, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(mBookshelfs, i, i - 1);
                }
            }
            mbookshelfAdapter.notifyItemMoved(fromPosition, toPosition);
//            Log.i("TAG", "fromPosition=" + fromPosition + "||toPosition=" + toPosition);
//            long front = 0;
//            long behind = 0;
//            if (toPosition == 0) {
//                fromPosition = 0;
//            } else if (toPosition == mBookshelfs.size() - 1) {
//                behind = System.currentTimeMillis();
//            } else {
//                front = mBookshelfs.get(toPosition).getOrder();
//                behind = mBookshelfs.get(toPosition + 1).getOrder();
//            }
//            mBookshelfPresenter.orderBookshelf(mBookshelfs.get(fromPosition).getId(),front,behind);
            //返回true表示执行拖动
            return true;
        }
 
Example 15
Source Project: LazyRecyclerAdapter   File: BindDragCallBack.java    License: MIT License 5 votes vote down vote up
@Override
public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
    super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
    int fromPosition = viewHolder.getAdapterPosition() - mAdapter.absFirstPosition();
    int toPosition = target.getAdapterPosition() - mAdapter.absFirstPosition();
    List dataList = mAdapter.getDataList();
    if (fromPosition >= 0 && toPosition >= 0 && dataList != null
            && toPosition < dataList.size() && fromPosition < dataList.size()) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                if (fromPosition < dataList.size() && toPosition < dataList.size()) {
                    Collections.swap(dataList, i, i + 1);
                }
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                if (fromPosition < dataList.size() && toPosition < dataList.size()) {
                    Collections.swap(dataList, i, i - 1);
                }
            }
        }
        //数据和item的位置不是一致的
        if (mAdapter != null) {
            mAdapter.notifyItemMoved(fromPos, toPos);
        }

        if (mMoveListener != null) {
            mMoveListener.onMoved(fromPosition, toPosition);
        }
        isDraged = true;
    }
    isSwiped = false;
}
 
Example 16
Source Project: awacs   File: VBStyleCollection.java    License: Apache License 2.0 5 votes vote down vote up
public void swap(int index1, int index2) {

    Collections.swap(this, index1, index2);
    Collections.swap(lstKeys, index1, index2);

    K key = lstKeys.get(index1);
    if (key != null) {
      map.put(key, index1);
    }

    key = lstKeys.get(index2);
    if (key != null) {
      map.put(key, index2);
    }
  }
 
Example 17
public static <E> List<E> pickNRandomElements(List<E> list, int n, Random r) {
    int length = list.size();

    if (length < n) return null;

    //We don't need to shuffle the whole list
    for (int i = length - 1; i >= length - n; --i)
    {
        Collections.swap(list, i , r.nextInt(i + 1));
    }
    return list.subList(length - n, length);
}
 
Example 18
@Override
public void onItemMove(int fromPosition, int toPosition) {
	Collections.swap(mDatas,fromPosition,toPosition);//交换数据
	notifyItemMoved(fromPosition,toPosition);
	isMove=true;
}
 
Example 19
Source Project: AndroidUtilCode   File: BaseItemAdapter.java    License: Apache License 2.0 4 votes vote down vote up
public void swapItem(@IntRange(from = 0) final int firstIndex,
                     @IntRange(from = 0) final int secondIndex, boolean notifyMoved) {
    Collections.swap(mItems, firstIndex, secondIndex);
    if (notifyMoved) notifyItemMoved(firstIndex, secondIndex);
}
 
Example 20
Source Project: a   File: PageLoader.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * 翻页完成
 */
void pagingEnd(PageAnimation.Direction direction) {
    if (!isChapterListPrepare) {
        return;
    }
    switch (direction) {
        case NEXT:
            if (mCurPagePos < curChapter().txtChapter.getPageSize() - 1) {
                mCurPagePos = mCurPagePos + 1;
            } else if (mCurChapterPos < book.getChapterListSize() - 1) {
                mCurChapterPos = mCurChapterPos + 1;
                mCurPagePos = 0;
                Collections.swap(chapterContainers, 0, 1);
                Collections.swap(chapterContainers, 1, 2);
                nextChapter().txtChapter = null;
                parseNextChapter();
                chapterChangeCallback();
            }
            if (mPageMode != PageAnimation.Mode.SCROLL) {
                mPageView.drawPage(1);
            }
            break;
        case PREV:
            if (mCurPagePos > 0) {
                mCurPagePos = mCurPagePos - 1;
            } else if (mCurChapterPos > 0) {
                mCurChapterPos = mCurChapterPos - 1;
                mCurPagePos = prevChapter().txtChapter.getPageSize() - 1;
                Collections.swap(chapterContainers, 2, 1);
                Collections.swap(chapterContainers, 1, 0);
                prevChapter().txtChapter = null;
                parsePrevChapter();
                chapterChangeCallback();
            }
            if (mPageMode != PageAnimation.Mode.SCROLL) {
                mPageView.drawPage(-1);
            }
            break;
    }
    mPageView.setContentDescription(getContent());
    book.setDurChapter(mCurChapterPos);
    book.setDurChapterPage(mCurPagePos);
    callback.onPageChange(mCurChapterPos, getCurPagePos(), resetReadAloud);
    resetReadAloud = true;
}