DenverCoder8
DenverCoder8

Reputation: 401

Is it possible to have an array containing both arrays and primitives in Java?

I'm doing a project in Java in which I'm looking at the frequency characters occur after each other character in a text. When I'm collecting my results, I'm storing them in a 2d array of ints. However, in the same results table, I want to store some results about the whole thing.

Is it possible to have an array where some of the elements are arrays, and others are primitives?

Upvotes: 1

Views: 99

Answers (4)

Pumuckline
Pumuckline

Reputation: 637

No, it is not working. There can only be objects OR primitives in one array. Anything else is just a workaround.

Upvotes: 1

korifey
korifey

Reputation: 3509

You can use boxed types, i.e. java.lang.Integer (So your array type must be Object[]), but better do make a new class for results Storage

Upvotes: 0

dimitrisli
dimitrisli

Reputation: 21401

In that case you would have to store Objects (primitives will autobox to Wrapper classes) and then when you read the entries you would need to instanceof the Object and then cast it safely.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425043

Yes, you can have Object[] and store a mix a types, although it would have to be the wrapper Integer (not the primitive int). (Note: you could "cheat" and save each int as a single-element array int[], thus making it an Object, but "don't try this at home")

But even if you could, an array isn't the right approach. Instead, create a class for this.

Try something like this:

public class FrequencyAnalysis {
    private int[] frequencies;
    private String info;
    private Date lastRun;
    // etc
}

Upvotes: 3

Related Questions