简体   繁体   中英

How to assign multiple data types to a single variable in java?

Right now I'm creating a bankApp and I don't have an idea how can I assign eg string name; double balance; etc. to a right one int PIN;. There is gonna be many accounts with different PINs and different values assigned to it . I tried making many objects :

    perInfo card1 = new perInfo();
    card1.PIN = 1994;
    card1.balance = 24.68;
    card1.isValid = true;

    perInfo karta2 = new perInfo();
    card2.PIN = 2002;
    card2.balance = 522.2;
    card2.isValid = false;

but I think it's too much work to do and it'll worsen performance of the app. I also tried making a list

    public bApp(int pin, double balance){
    this.pin = pin;
    this.balance = balance;}

    List<bApp> pass = new ArrayList<>();
        pass.add(new bApp(1994, 568.45));
        pass.add(new bApp(2002, 13866.24));

but it didn't work ,because I couldn't call the PIN to check that if user has provided the right one PIN . Arrays are also not suited for this.

The data structure you are looking for is a Map. Take a look at HashMap and you'll want to key off of whatever value you are using to lookup.

For example if you wanted to lookup a user by pin:

Map<Integer, bApp> passes = new HashMap<>();
passes.put(1994, new bApp(1994, 568.45));
passes.put(2002, new bApp(2002, 13866.24));

You could use a HashMap for this and use the pin as a key and store the object in the HashMap. This would allow you to access each card using only the pin. However, this would not allow for duplicate pins. I would recommend that you reference each account by a unique ID and check the pin within the object itself.

HashMap<Integer, Account> accounts = new HashMap<Integer, Account>();
accounts.put(12345678, new Account(1994, 568.4));

You can then get the account using the unique ID and check if the pin is correct.

Account acc = accounts.get(uniqueID);
if(acc.pin == enteredPin){
    //Whatever you need to do
}

I think it would be simpler to just have an array of the different cards, with each pin being set to the array address:

bApp[] cards = new bApp[NUMBER_OF_CARDS];
cards[0] = new bApp(0, 568.45);
// ...
cards[2002] = new bApp(2002, 13866.24);

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