0
我這裏有三類:爲什麼當我的類的實例不應該爲null時,我會得到空值?
abstract class ParentClass{
String ide;
ArrayList args;
ParentClass from_type;
ParentClass to_type;
}
class Classone extends ParentClass{
String ide;
ArrayList<ParentClass> args;
public Classone(ParentClass from_type, ParentClass to_type){
this.from_type = from_type;
this.to_type = to_type;
}
public Classone(String ide, ArrayList<ParentClass> args){
this.ide = ide;
this.args = args;
}
@Override
public String toString() {
String result = "";
if (ide == null) {
return from_type.toString() + " -> " + to_type.toString();
}
else {
if (args.size() == 0) {
return ide;
}
else if (args.size() == 2) {
result = args.get(0).toString() + " " + ide + " " + args.get(1).toString();
return result;
}
else {
return "Wrong number";
}
}
}
}
class Classtwo extends Classone{
ParentClass from_type;
ParentClass to_type;
public Classtwo(ParentClass from_type, ParentClass to_type){
super(from_type, to_type);
}
}
當我創造一些實例如下圖所示:
的sameType
方法是樓下:
public static boolean sameType(ParentClass t1, ParentClass t2){
if (t1 instanceof Classone && t2 instanceof Classone) {
if (t1.ide != null && t2.ide != null) {
System.out.println(t1.ide);
System.out.println(t2.ide);
return t1.ide == t2.ide;
}
else {
return false;
}
}
else {
return false;
}
}
Classone a = new Classone("bool", new ArrayList<ParentClass>());
Classone b = new Classone("bool", new ArrayList<ParentClass>());
System.out.println(sameType(a,b));
將打印false
再沒有別的,所以這意味着a.ide
和b.ide
這裏是null
;他們應該是字符串bool
; 任何人都可以幫助我嗎?
這並沒有幫助你沒有向我們展示'sameType'。請提供[mcve]。 –
您是否正在測試「a.ide」和「b.ide」的平等或對象身份?也就是說,你用'=='(對象標識)還是'.equals()'測試?請參閱http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java –
嗨,相同的類型現在附加 –