简体   繁体   中英

How to add to an arraylist of class type

Ok so this is what I have

public class Register {

    public String propertyID;
    public String PPSNumber;

    Register(String aPropertyID, String aPPSNumber) {
        propertyID = aPropertyID;
        PPSNumber = aPPSNumber;
    }

    public void setPPSNumber(String aPPSNumber) {
        PPSNumber = aPPSNumber;
    }

    public String getPPSNumber() {
        return PPSNumber;
    }

    public String getPropertyID() {
        return propertyID;
    }
}

Then I have this

public static ArrayList<Register> registers = new ArrayList<Register>();

public static void main(String[] args) {

    String userInput1 = "", userInput2 = "", userInput3 = "";
    userInput1 = JOptionPane.showInputDialog("Enter your PPSNumber");
    userInput2 = JOptionPane.showInputDialog("Enter your propID");

    registers.add("number", "id");
}

I don't understand why It wont let me add to the ArrayList. Is there some way of adding class types to ArrayLists?

Try this instead :

registers.add(new Register("number","id"));

EDIT 1: To answer your question, you can create a separate "register" and the use the getters :

Register aRegister = new Register("number","id");
registers.add(aRegister);
System.out.println(aRegister.getPropertyID()+" "+ aRegister.getPPSNumber());

Your List is of type Register so you need to add object of Register class only.

Nothing wrong in create as many Register objects as required.

You can implement toString() method inside Register class then the below sysout will work given the register variable is initialized with Register object. Check this How to override toString() properly in Java? to know about toString implementation.

System.out.println(register)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM