我知道collections.reverse方法使用swap函数,但我试图确定如何基本上只使用add和remove方法创建交换方法。
我也无法创建新列表。
伪代码的想法
MongoClient.connect('mongodb://localhost:27017/norad', function(err, db){
if (err) return router.error( Error(err) );
db.collection('users', function(err, coll){
if (err) return router.error( Error(err) );
coll.insert({
'email' : useremail
,'pass' : userpass
,'total_req': 0
,'threshold_req': 0
,'threshold_start_time': 0
,'ak' : activation_key
,'activated': false
,'adm' : false
,'iat' : iat
,'created' : iat
,'modified' : iat
}
,function(err, writeResults){
console.log( writeResults );
if ( err && err.code == 11000 ) return router.error( ErrorHandler('User already exists.', 'Conflict', 409) )
if ( err ) return router.error( Error(err) );
var r = {'email': writeResults.ops[0].email
,'Response':'Your activation code has been emailed to the address used in registration. Please check your email and follow the instructions for account activation.'
}
,scallback = function(){ return router.submit(r) }
// send the activation email to the user
,res = ActivationEmail(activation_key, useremail, scallback, router)
;
if ( res instanceof Error ) router.error( Error(err) );
}
);
});
});
并继续这样做?
我显然需要把它放到for循环中 我觉得这很容易,我只是在思考它。
答案 0 :(得分:3)
很简单,Collections类reverse()中有一个静态方法,所以只需执行:
Collections.reverse(yourListHere);
好的,所以我刚读过你只能使用添加和删除,请检查:
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main (String[] args){
List<Integer> lista = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,4));
for (int i = 0; i < lista.size(); i++) {
lista.add(i, lista.remove(lista.size() - 1));
}
System.out.println(lista);
}
}
答案 1 :(得分:1)
ArrayList<Object> list = getArraylist();
for(int i = 0; i < list.size(); i += 1) {
list.add(i, list.get(list.size() - 1));
list.remove(list.size() - 1);
}
足够简单。
答案 2 :(得分:0)
import java.util.ArrayList;
import java.util.List;
public class ReverseList {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
int median = list.size()/2;
for (int i = 0, j = list.size()-1; i < median; i++,j--) {
swap(list, i, j);
}
list.forEach(System.out::println);
}
public static void swap(List<Integer> list, int leftPointerIndex, int rightPointerIndex) {
int leftElement = list.get(leftPointerIndex);
int rightElement = list.get(rightPointerIndex);
list.set(leftPointerIndex, rightElement);
list.set(rightPointerIndex, leftElement);
}
}