我試圖通過向上或向下移動選定的項目來修改Map
中的元素列表。我的想法是記住所選項目旁邊的元素。因爲這些元素都在地圖中,所以我發現要做到這一點非常困難,儘管我使用了LinkedHashMap
如果有人能給我一個關於如何去做的想法,我將不勝感激。將選定的元素向上或向下移動
注:我已經概括了這個問題,下面的代碼只是一個參考。
public void moveUp(ActionEvent evt) {
List<String> selectedItems = myBean().getSelectedItems();
if(selectedItems.isEmpty()) return;
Map<String, String> avlbleItems = new LinkedHashMap<String, String>(myBean().getListBoxItems());
List<String> avlbleItemsList = new ArrayList<String>(myBean().getListBoxItems().values());
int size = avlbleItems.size();
List<String> tail = new ArrayList();
List<String> head = new ArrayList();
int buf = 0,k = 0,j = 0,m = 0,n = 0;
try {
label:
for (Iterator it = selectedItems.iterator(); it.hasNext();buf++) {
String st = (String) it.next();
if(buf==0) {
for (int i = 0; i < size; i++) {
if(avlbleItemsList.get(i).equals(st)) {
k = i-1;
m = k+2;
n = m;
}
}
if(k < 0) return;
if(k == 0) continue label;
}
if(n < size && selectedItems.contains(avlbleItemsList.get(n))) {
n++;
}
if(k+2 < size && !selectedItems.contains(avlbleItemsList.get(k+2))) {
m++;
}
if(!it.hasNext()) {
for (int i = 0; i < size; i++) {
if(avlbleItemsList.get(i).equals(st)) {
j = i+1;
if(j == size) break label;
if(j < size) {
tail = avlbleItemsList.subList(j, size);
}
}
}
}
}
avlbleItems.clear();
for (Iterator ite = head.iterator(); ite.hasNext();) {
String st = (String) ite.next();
avlbleItems.put(st, st);
}
for (Iterator it = selectedItems.iterator(); it.hasNext();) {
String st = (String) it.next();
avlbleItems.put(st, st);
}
avlbleItems.put(avlbleItemsList.get(k), avlbleItemsList.get(k));
for (int i = n; i < j-1; i++) {
avlbleItems.put(avlbleItemsList.get(i), avlbleItemsList.get(i));
}
for (Iterator it = tail.iterator(); it.hasNext();) {
String st = (String) it.next();
avlbleItems.put(st, st);
}
} catch (IndexOutOfBoundsException e) {
handleException();
return;
} catch (NoSuchElementException e) {
handleException();
return;
} catch (IllegalArgumentException e) {
handleException();
return;
}
}