如何将多个变量值存储到单个数组或列表中? [英] How can I store multiple variable values into a single array or list?

查看:718
本文介绍了如何将多个变量值存储到单个数组或列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下变量,它们是数据类型的混合,包括整数,字符串,双精度数和数组.我已经有了填充每个变量所需的方法.我现在需要的是将所有变量收集到一行数据中,然后将该数据显示在另一个类中以供以后使用.数据应保持相同的数据类型,以便我可以在另一个类中使用它们.同一行数据也需要存储一次以上.以下是我希望如何存储数据的演示.

So I have the below variables which are a mix of data types including integers, strings, doubles and arrays. I already have the methods required to fill each variable. All I need now is to gather all the variables into a single row of data, and than display that data in another class for later use. The data should be kept with same data type so I can use them in another class Also the same row of data need to be stored more than once. Below is a demonstration of how I want the data to be stored.

Ticket No = 1, Ticket Type = "Lotto",   Ticket Value = 2.50, Numbers = {1,2,3,4,5}

Ticket No = 2, Ticket Type = "Jackpot", Ticket Value = 2.50, Numbers = {4,1,4,5,5}         

请为我提供最简单的解决方案.谢谢.

Kindly provide me with the simplest solution as possible. Thanks.

int id;
String ticketType;
double value;
int[] numbers= new int[5];

推荐答案

您可以使用ArrayList<? extends Object>,然后将Object强制转换为每个项目索引的正确类型.但这很丑陋,最好创建一个Ticket类,该类具有每个属于票证的值的类字段.像这样:

You could use an ArrayList<? extends Object> and then cast from Object to the correct type for each item index. But this is ugly, and it's far better to create a Ticket class which has class fields for each value which belongs to a ticket. Something like this:

class Ticket {
    int ticketNumber;
    TicketType ticketType;
    int ticketValueInPence;
    List<Integer> ticketDrawNumbers;

    enum TicketType {
        LOTTO,
        JACKPOT
    }
}

然后,您可以在新类中定义构造函数和getter方法,以便可以创建具有特定值的票证,然后检索为特定票证设置的值.

Then you can define a constructor and getter methods within your new class, so that you can create a ticket with specific values, and then retrieve the values set for a particular ticket.

一旦有了自定义类型,就可以使用以下代码将该类型的对象添加到列表中:

Once you've got a custom type you can add objects of that type to a list with code like this:

List<Ticket> ticketList = new ArrayList<>();
ticketList.add(anyTicket);

远胜于从Object进行投射.

这篇关于如何将多个变量值存储到单个数组或列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆