简体   繁体   中英

How can I store multiple variable values into a single array or list?

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];

You could use an ArrayList<? extends Object> 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
    }
}

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);

Far better than casting from Object .

A class abstraction, which would represent a Ticket , would be the simplest way to go about this. This is the cleanest way to keep all of the information about a ticket together without having to (really) worry about the underlying data structures.

public class Ticket {

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

    // various methods like getId, getTicketType, setId, setTicketType
    // would follow from here.

}
import java.util.ArrayList;
import java.util.List;

public class Ticket {

    private int id;
    private String type;
    private double value;
    private int[] numbers;

    public Ticket(int id, String type, double value, int[] numbers) {
        this.id = id;
        this.type = type;
        this.value = value;
        this.numbers = numbers;
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();

        builder.append("Ticket no  = " + id + ", ");
        builder.append("Ticket type = " + type + ", ");
        builder.append("Ticket Value = " + value + ", ");
        builder.append("Numbers = {");

        for (int i = 0; i < 5; i++)
            builder.append(i != 4 ? numbers[i] + "," : numbers[i]);

        builder.append("}");

        return builder.toString();
    }

    public static void main(String[] args) {
        List<Ticket> ticketList = new ArrayList<>();

        ticketList.add(new Ticket(1, "Lotto", 2.50, new int[]{1,2,3,4,5}));
        ticketList.add(new Ticket(2, "Jackpot", 2.50, new int[]{4,1,4,5,5}));

        for (Ticket t: ticketList) {
            System.out.println(t);
        }
    }

}

Well, I kind of did everything for you, however as everyone mentioned it's actually very essential concept in object oriented programming. Creating new data types using classes just like structs in C. Therefore you can use this type in lists and arrays. I hope it is useful and you've learned something.

Probably I should mention the toString() method. It's implicitly called when you call the System.out.println() method. In this way you can get a nice string representatin of your data type.

You should create a new class called Ticket. It would look something like this:

public class Ticket {

int id;
String ticketType;
double value;
int[] numbers;

public Ticket(){}

public Ticket(int id, String ticketType, double value, int[] numbers){
    this.id = id;
    this.ticketType = ticketType;
    this.value = value;
    this.numbers = numbers;
}

public int getId() {
    return id;
}

public String getTicketType() {
    return ticketType;
}

public double getValue() {
    return value;
}

public int[] getNumbers() {
    return numbers;
}

public void setId(int id) {
    this.id = id;
}

public void setTicketType(String ticketType) {
    this.ticketType = ticketType;
}

public void setValue(double value) {
    this.value = value;
}

public void setNumbers(int[] numbers) {
    this.numbers = numbers;
}
}

Then, in your main class, create an ArrayList in one of two ways. Using your examples . . .

    //You can create a ticket like this
    Ticket ticketOne = new Ticket();
    ticketOne.setId(1);
    ticketOne.setTicketType("Lotto");
    ticketOne.setValue(2.50);
    ticketOne.setNumbers(new int[]{1, 2, 3, 4, 5});

    //Alternatively, you can do it all at once
    Ticket ticketTwo = new Ticket(2, "Jackpot", 2.50, new int[]{4,1,4,4,5});

    ArrayList<Ticket> listOfTickets = new ArrayList<>();
    listOfTickets.add(ticketOne);
    listOfTickets.add(ticketTwo);

You can use:

String[][][][] ticketInfo;

and convert integer and double values back to int and double when needed, by using

Integer.parseInt(ticketInfo[?][?][?][?]) and Double.parseDouble(ticketInfo[?][?][?][?])

'?' means index which you needed

Records

Other Answers are correct about defining a class to hold your multiple values.

In Java 16 and later, defining such a class is much easier with the records feature. Define your class as a record when its main job is to transparently and immutably carry data. The compiler implicitly creates a constructor, the getters, hashCode & equals , and toString .

Always use BigDecimal for fractional money, never the floating point types float / double .

record Ticket ( int number , Kind kind , BigDecimal price , int[] numbers ) {}

Kind there should be an enum, as indicated in Answer by Bobulous .

Instantiate like any other class.

Ticket ticket = new Ticket( 1 , Kind.LOTTO , new BigDecimal( "2.50" ) , {1,2,3,4,5} ) ;

I am partial to using List rather than arrays. Plus we can make a list that is unmodifiable , which is more appropriate in a record .

record Ticket ( int number , Kind kind , BigDecimal price , List< Integer > numbers ) {}

… and …

Ticket ticket = new Ticket( 1 , Kind.LOTTO , new BigDecimal( "2.50" ) , List.copyOf( {1,2,3,4,5} ) ) ;

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