我想扩展 AbstractStringBuilder 并获得一个与 StringBuilder 相同的类,但具有与 String.hashCode() 相同的 hashCode() 方法。目的是使用这个新的子类作为哈希表中的键。我想尝试使用 Hashtable 和这个新的子类,看看会发生什么,因为最终我想解决一些内存问题,而 StringBuilder 解决了其中一些问题,但不是全部。所以,这是子类,
import java.lang.*;
public final class StringCon extends AbstractStringBuilder implements java.io.Serializable, CharSequence
{
public StringCon()
{
super( 16);
}
public StringCon( int capacity)
{
super( capacity);
}
public StringCon( String str)
{
super( str.length() + 16);
append( str);
}
public StringCon append( Object obj)
{
return append( String.valueOf( obj));
}
public StringCon append( String str)
{
super.append( str);
return this;
}
public StringCon delete( int start, int end)
{
super.delete( start, end);
return this;
}
public StringCon delete( int start)
{
super.delete( start, this.length());
return this;
}
public int indexOf( String str)
{
return indexOf( str, 0);
}
public int indexOf( String str, int fromIndex)
{
return String.indexOf( value, 0, count, str.toCharArray(), 0, str.length(), fromIndex);
}
public int hashCode()
{
int hash = 0;
int h = hash;
if( h == 0 && count > 0)
{
int off = 0;
char val[] = value;
int len = count;
for( int i = 0; i < len; i++)
h = 31*h + val[ off++];
hash = h;
}
return h;
}
}
我只实现我将要使用的方法。问题是,
1) 编译器找不到符号值、计数甚至关键字 super。这些符号在 AbstarctStringBuilder 中定义,并且 StringBuilder 可以自由使用它们。为什么?
2) 编译器找不到方法 AbstractStringBuilder.substring()。为什么?
3)我收到错误,
error: type argument StringCon is not within bounds of type-variable E
在声明中
hth = ( j + 1 < al.size()) ? new Hashtable< StringCon, LinkedList< StringCon>>( al.get( j + 1).size(), 0.75F) : null;
4)我收到错误
error: method containsKey in class Hashtable<K,V> cannot be applied to given types;
if( hth.isEmpty() || !hth.containsKey( nextKey))
^
required: Object
found: StringCon
reason: actual argument StringCon cannot be converted to Object by method invocation conversion
where K,V are type-variables:
K extends Object declared in class Hashtable
V extends Object declared in class Hashtable
其中 nextKey 是 StringCon 对象。
上面的各种方法是我从 StringBuilder 和 String 类复制的。
我哪里不明白,我的错误在哪里?我在 Hadoop 环境中使用上述所有内容(如果这有任何重要性的话)。
最佳答案
java.lang.AbstractStringBuilder
不是 public
,因此只能由 java.lang
中的其他类扩展。尝试编译代码会出现第一个错误:
StringCon.java:3: java.lang.AbstractStringBuilder is not public in java.lang;
cannot be accessed from outside package
通常不建议使用可变类作为哈希表中的键 ( Are mutable hashmap keys a dangerous practice? )。可能有更好的方法来解决您的问题:
because in the end I want to solve some memory issues which StringBuilder solves some of them but not all of them
考虑直接询问有关内存问题的问题。
关于java - 扩展 AbstractStringBuilder 并在哈希表中使用子类时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18932564/