确保我使用Randomness获得一个条目

时间:2013-03-01 20:10:12

标签: java random string-utils

我正在尝试使用以下方法生成随机列,并在生成列后,我在SELECT sql中使用这些列。

final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + "  from " + table.getTableName() + " where id = ?";

/**
 * A simple method to get the column names in the order in which it was
 * inserted
 * 
 * @param columns
 * @return
 */
private String getColumns(final List<String> columns) {
    List<String> copy = new ArrayList<String>(columns);
    Collections.shuffle(copy);

    int rNumber = random.nextInt(columns.size());

    List<String> subList = copy.subList(0, rNumber);
    Collections.sort(subList, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
        }
    });
    return StringUtils.join(subList, ",");
}

问题陈述: -

有时我看到columnsList值为空,如果为空,则selectSql将无效,因为,之前会有额外的from keyword。我怎样才能确保getColumns每次至少返回一个条目。

我相信nextInt会在0 (inclusively) and n (exclusively)之间生成随机数。所以它有时可能会选择0,任何方法都可以在1(inclusively) and n (exclusively)

之间生成随机数

1 个答案:

答案 0 :(得分:1)

一种方法是:

return subList.isEmpty() ? "1" : StringUtils.join(subList, ",");

但我认为最好将selectSql修改为

final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE " + columnsList + "  from " + table.getTableName() + " where id = ?";

然后

return subList.isEmpty() ? "" : ","+StringUtils.join(subList, ",");

如果你想从随机中得到一个值,你也可以使用它:

int rNumber = 1+random.nextInt(columns.size()-1);