Failed to store values in ArrayList of class object. (CODE EDITED)

后端 未结 2 608
夕颜
夕颜 2021-01-27 10:19

This is basically a Java code converter. It involves a GUI let user input class type, name and method. To store the values, I\'ve created a class VirtualClass with

相关标签:
2条回答
  • 2021-01-27 10:23

    You have a couple of problems with your code. But mainly, you creational logic does not make much sense. You should not add an instance into your Static collection using a method of the instance. My advice would be to use a static factory method to do this. Something like this instead :

    public class VirtualClass {
    
    private static List<VirtualClass> classes = new ArrayList<VirtualClass>();
    private boolean isPrivate;
    private String className;
    private String methodName;
    
    //A private constructor
    private VirtualClass(String name, String method, boolean isP){
        this.className = name;
        this.isPrivate = isP;
        this.methodName = method;
    }
    
    private void setClassName(String className){
        this.className = className;
    }
    
    private void getClassName(){
        return className;
    }
    
    public static VirtualClass createClass(String name, String method, boolean isP){
        VirtualClass virtualClass = new VirtualClass(String name, String method, boolean isP);
        classes.add(virtualClass);
        return virtualClass;
    }
    }
    

    The way your code is done now, the problems can be in a lot of places in your client classes. This structure is safer and generally used.

    Also you should not type your collection with ArrayList but use the implemented interface instead, List. how to use an array list?

    0 讨论(0)
  • 2021-01-27 10:43

    From information you posted, seems strange that you initiate VirtualClass stObject into actionPerformed method. Its mean that each time you recreate your object.

    Make your VirtualClass stObject to be global for example, like:

    private VirtualClass stObject;
    
    ...
    
    stObject = new VirtualClass();
    
    private class Handler implements ActionListener{
    
        public void actionPerformed(ActionEvent event){
    
        ...
    
       stObject.createClass(cName, mName, isP);
    
    0 讨论(0)
提交回复
热议问题