我有一个HashSet<String>
,其中包含名为shingles
的字符串(如果您使用字符串&#34; Fizzbuzz&#34;并将其分解为带状疱疹,您可以&#39; d得到&#34; Fi&#34;,&#34; iz&#34;,&#34; zz&#34;,&#34; zb&#34;,&#34; bu&#34;,&#34; uz&#34;,&#34; zz&#34;。不重要,但这就是这个背景下的一块木瓦。)
我试图通过以下方法返回一串HashSet的内容:
public String getShinglesAsString() {
String shingles = "";
for (String shingle : this.shingles) {
shingles += shingle + " ";
}
return shingles;
}
for (String shingle : this.shingles)
抛出ClassCastException。具体邮件为Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.CharSequence
。
我也尝试过使用Iterator对象,我也遇到了同样的问题。这是我从代码输入到构造函数的字符串生成带状疱疹的代码:
// Will generate a new set of shingles based on sentence
public void generateShingles() {
shingles = new HashSet<>();
for (int i=0; i<getSentence().length()-1; i++) {
getShingles().add(getSentence().charAt(i) + getSentence().charAt(i+1));
}
}
编辑:这是minmal, complete, verifiable example:
public class SentenceWithShingles {
private String sentence;
private Set<String> shingles;
// Constructor
public SentenceWithShingles(String sentence) {
this.sentence = sentence;
generateShingles();
}
// Will generate a new set of shingles based on sentence
public void generateShingles() {
shingles = new HashSet<>();
for (int i=0; i<getSentence().length()-1; i++) {
getShingles().add(getSentence().charAt(i) + getSentence().charAt(i+1));
}
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
public Set getShingles() {
return shingles;
}
public String getShinglesAsString() {
String shingles = "";
for (String shingle : this.shingles) {
shingles += shingle + " ";
}
return shingles;
}
}
答案 0 :(得分:0)
错误在于:
getShingles().add(getSentence().charAt(i) + getSentence().charAt(i+1));
该行将两个字符加在一起。没有连接它们。
getShingles().add(getSentence().charAt(i) + "" + getSentence().charAt(i+1));
将强制使用正确的语义。