Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Base64是确定性的(Apache Commons lib还是其他)?_Java_Scala_Base64_Apache Commons - Fatal编程技术网

Java Base64是确定性的(Apache Commons lib还是其他)?

Java Base64是确定性的(Apache Commons lib还是其他)?,java,scala,base64,apache-commons,Java,Scala,Base64,Apache Commons,我正在使用Apache Commons库中的Base64编码器。现在,要么我的运行时/IDE发生了一些有趣的事情,要么它们的Base64编码(或作为规范的Base64)实现是不确定的: val test = Base64.encodeBase64("hello".getBytes).toString val test2 = Base64.encodeBase64("hello".getBytes).toString val test3 = Base64.encodeBase64("hello".

我正在使用Apache Commons库中的Base64编码器。现在,要么我的运行时/IDE发生了一些有趣的事情,要么它们的Base64编码(或作为规范的Base64)实现是不确定的:

val test = Base64.encodeBase64("hello".getBytes).toString
val test2 = Base64.encodeBase64("hello".getBytes).toString
val test3 = Base64.encodeBase64("hello".getBytes).toString

以上每一项都会产生不同的结果。这是预期的吗?我是用Scala写的…

您发布的Scala代码的等效Java代码是:

String test = Base64.encodeBase64("hello".getBytes()).toString();
String test2 = Base64.encodeBase64("hello".getBytes()).toString();
String test3 = Base64.encodeBase64("hello".getBytes()).toString();
这将为每个
Base64.encodeBase64(“hello”.getBytes())
打印
byte[]
数组对象的
toString()
,这些对象将是不同的对象,因此对控制台的输出不同。它执行
Object
类的方法,根据Javadocs的说法:

返回对象的字符串表示形式

class对象的toString方法返回一个字符串,该字符串由对象作为实例的类的名称、at符号字符“@”和对象哈希代码的无符号十六进制表示形式组成

要获得正确的
字符串
表示,请使用方法。打印正确结果的示例Java代码如下所示:

String test = Arrays.toString(Base64.encodeBase64("hello".getBytes()));
String test2 = Arrays.toString(Base64.encodeBase64("hello".getBytes()));
String test3 = Arrays.toString(Base64.encodeBase64("hello".getBytes()));

对数组调用toString()可能会返回单个数组的JVM内存地址,因此,每个Base64.encodeBase64(“hello”.getBytes())将返回不同的数组,每个数组上的toString()将返回不同的地址。

Ahhh!这是我对Array.toString的滥用!哦!谢谢:)只是一个提示:在没有指定编码的情况下,不要对字符串使用getBytes(),特别是当您将其传输到另一个系统时,这可能是在执行base64编码时的情况。否则,如果发生Base64编码和Base64解码的计算机上的默认编码不同,您可能会遇到问题。在Scala中,执行此操作的一个简单方法是“.toList.toString”列表始终打印其内容而不是引用。不一定是内存地址。请参考Javadocs。@是的,我知道这是一个被称为“身份散列码”的东西,在外行的术语中,它可以被认为是一个内存地址。我用“可能”这个词的原因