RandomStringUtils 是否创建确定性或可重复的序列? [英] Does RandomStringUtils create a deterministic or reproducible sequence?

查看:128
本文介绍了RandomStringUtils 是否创建确定性或可重复的序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 应用服务器上,我们使用 RandomStringUtils.randomAlphabetic() 顺序创建 HTML-ID,以迭代方式重复出现类似的段落.

On a Java application server we use RandomStringUtils.randomAlphabetic() to sequentially create HTML-IDs for recurring similar paragraphs in an iterating manner.

通过这些生成的 ID,我们允许进行内页锚点导航(点击时不会触发页面加载).

Via these generated IDs, we allow for an inner-page anchor navigation (without a page load triggered upon click).

现在的问题是,我能否将这些生成的 ID 也用于从外部页面链接到此目标的 URL?根据我的观察,对同一页面的后续请求,会创建相同的 ID 序列.如果生成的 randomAlphabetic 序列确实是可预测的(也可以通过多个页面加载),我们不仅可以将这些链接用于内页导航,还可以用于从外部引用的链接,因为第一个,第二个, 第三, ... 生成的 ID 将始终相同.

Now the question is, can I use these generated IDs also for URLs linking from external pages to this target? According to my observation, subsequent requests to the same page, create the same sequence of IDs. If the generated sequence of randomAlphabetic is indeed predictable (also over multiple page loads), we could not only use these links for inner-page navigation, but also for links referring from outside, since the first, second, third, ... generated ID would always be the same.

推荐答案

如果随机"对于一个段落的给定文本字符串,ID 始终相同(即 ID 仅是段落文本的函数),那么您应该考虑散列函数,而不是伪随机数生成器,例如 randomAlphabetic.(我假设对于您识别页面部分的用例,为不同的文本字符串生成重复 ID 的风险可以忽略不计.但是,如果您不能容忍这种风险,不应使用散列函数.)为此目的有多种散列函数;甚至 java.lang.String.hashCode() 也可以在这里工作,因为 此方法的 Java 文档 指定了它使用的确切算法.

If the "random" ID is always the same for a given text string of a paragraph (that is, the ID is solely a function of a paragraph's text), then you should consider hash functions, rather than pseudorandom number generators such as randomAlphabetic. (I assume that for your use case of identifying parts of a page, the risk of generating duplicate IDs for different text strings is negligible. If you can't tolerate this risk, though, hash functions should not be used.) There are many kinds of hash functions for this purpose; even java.lang.String.hashCode() will work here since the Java documentation for this method specifies the exact algorithm it uses.

此外,randomAlphabetic 不是确定性的";从你想要的意义上来说,有两个原因:

Moreover, randomAlphabetic is not "deterministic" in the sense you want for two reasons:

  • 您无法设置该方法使用的底层生成器的种子(RandomStringUtils 存储一个静态 PRNG 变量,该变量使用未定义的种子初始化,即 new Random()).
  • RandomStringUtils.randomAlphabetic(以及其他 RandomStringUtils 方法)的文档没有指定它用于生成随机字符串的确切算法.
  • You can't set the seed of the underlying generator the method uses (RandomStringUtils stores a static PRNG variable initialized with an undefined seed, namely new Random()).
  • The documentation for RandomStringUtils.randomAlphabetic (among other RandomStringUtils methods) doesn't specify the exact algorithm it uses to generate random strings.

这篇关于RandomStringUtils 是否创建确定性或可重复的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆