我有以下代码,我正在创建一个数组并尝试在其中存储对象.在运行时,我得到一个ArrayStoreException.
import java.lang.reflect.Array;
public class GenericsArrayCreation<T> {
public static <T> void Test(T[] A){
@SuppressWarnings("unchecked")
T[] temp = (T[]) Array.newInstance(A.getClass(), A.length);
for(int i = 0;i<temp.length;i++){
temp[i] = A[i];
System.out.println(temp[i].toString());
}
}
public static void main(String[] args){
String[] strs = {"a", "b", "c"};
GenericsArrayCreation.Test(strs);
}
}
Run Code Online (Sandbox Code Playgroud)
我莫名其妙地明白这是因为这句话
T[] temp = (T[]) Array.newInstance(A.getClass(), A.length);
Run Code Online (Sandbox Code Playgroud)
为什么这是错的?A.getClass()在运行时返回一个String,所以temp应该是一个字符串数组.在那种情况下,为什么作业temp[i] = A[i]不起作用?
我想在这个类中重写equals()方法.我在覆盖equals()方法时遵循通常的规则但是我将对象类型转换为我的类类型
但是在我的equals()方法中,只有当对象具有相同的泛型类型时,我才想返回true.
如何在equals()方法中检查实例的运行时类型?
这是我的代码:
public class GenericsRunTimeType<T> {
private T foo;
public GenericsRunTimeType(T foo){
this.foo = foo;
}
@Override
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
// Before doing this I want to test if obj and this are of the same generic type
GenericsRunTimeType other = (GenericsRunTimeType) obj;
if(other.equals(obj))
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
}
我正在搜索正则表达式 - ".(冲突副本. ".我为此编写了以下代码
String str = "12B - (conflicted copy 2013-11-16-11-07-12)";
boolean matches = str.matches(".*(conflicted.*");
System.out.println(matches);
Run Code Online (Sandbox Code Playgroud)
但我得到了例外
线程"main"中的异常java.util.regex.PatternSyntaxException:索引15附近的未闭合组.(冲突.
我知道编译器认为这(是模式组的开始.我试图(通过添加来逃避,\(但这不起作用.
谁能告诉我如何逃离(这里?