Java 如何向对象ArrayList添加多个值?
问题应该在Java 如何向对象ArrayList添加多个值?,java,class,oop,object,arraylist,Java,Class,Oop,Object,Arraylist,问题应该在createClass()方法上。。。使用类是否错误。添加(此) private static ArrayList classes=new ArrayList(); 私有布尔值是私有的; 私有字符串类名; 私有字符串methodName; public void setVirtualClass(字符串名称、字符串方法、布尔值){ this.className=名称; this.isPrivate=isP; this.methodName=方法; } public void create
createClass()
方法上。。。使用类是否错误。添加(此)
private static ArrayList classes=new ArrayList();
私有布尔值是私有的;
私有字符串类名;
私有字符串methodName;
public void setVirtualClass(字符串名称、字符串方法、布尔值){
this.className=名称;
this.isPrivate=isP;
this.methodName=方法;
}
public void createClass(字符串名称、字符串方法、布尔值){
this.className=名称;
this.isPrivate=isP;
this.methodName=方法;
类。添加(此);
}
有关该问题的更多详细信息:我想您希望保留所有已创建类的记录 通常在构造函数中传递
this
是不好的做法,因为根据定义,this
尚未构造。在这种情况下,我不认为它会引起问题,但它肯定闻起来不对
我会考虑使用<代码>静态< /代码>工厂方法或另一种工厂模式,这样你就可以拆分对象创建和实例存储。
< P>除非你告诉你要做什么,否则没有人能告诉你它是对还是错。 如果您正在做的是:(假设您的类名为Foo)诸如此类,那么是的,你可能错了。因为您所做的只是更改唯一具有不同属性的Foo实例,并将相同的对象添加到列表中。您想将什么添加到“类”列表中?不要一次又一次地问相同的问题。学习使用调试器,并逐步了解代码的实际执行情况。这并不是天生的错误,但它看起来不像是好的设计。不管怎样,静态可变变量总是一种气味。你的问题应该是自包含的:问题是什么?
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
Foo foo = new Foo();
foo.createClass("Blablabla", "method1", true);
foo.createClass("AnotherClass", "method2", true);