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

The following examples show how to use java.util.Collections#swap() . 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
Source File: NeighborPermutationRevert.java    From opt4j with 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 2
Source File: Command.java    From copybara with 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 3
Source File: AddressServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: PortfolioStructureDaoImpl.java    From olat with 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 5
Source File: StepConfigAction.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 6
Source File: Sampler.java    From ProximityForest with GNU General Public License v3.0 5 votes vote down vote up
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 7
Source File: MifareReadSetupDialogViewModel.java    From Walrus with GNU General Public License v3.0 5 votes vote down vote up
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 8
Source File: VBStyleCollection.java    From awacs with 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 9
Source File: BindDragCallBack.java    From LazyRecyclerAdapter with 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 10
Source File: BookshelfFragment.java    From MaterialHome with 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 11
Source File: DeviceFinder.java    From brailleback with 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 12
Source File: GeneticAlgorithmTest.java    From Nest4J with 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 File: SwapElementsOfVectorExample.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
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 14
Source File: NewsChannelAdapter.java    From ZZShow with 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 15
Source File: BaseBookListAdapter.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@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 16
Source File: LanguagesAdapter.java    From FirefoxReality with Mozilla Public License 2.0 5 votes vote down vote up
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 17
Source File: StickerManagementAdapter.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
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 18
Source File: BaseItemAdapter.java    From AndroidUtilCode with 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 19
Source File: BaseRecyclerViewAdapter.java    From Collection-Android with MIT License 4 votes vote down vote up
@Override
public void onItemMove(int fromPosition, int toPosition) {
	Collections.swap(mDatas,fromPosition,toPosition);//交换数据
	notifyItemMoved(fromPosition,toPosition);
	isMove=true;
}
 
Example 20
Source File: PageLoader.java    From a with 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;
}