How to create a 2D array of containing different data types

Viewed 63

My goal is to have an array like this: {{Object, int}, {Object, int}} where the integer represents a count of how many of the previously indicated object there are. I have looked into java generics, but I can't seem to get it right. What I have so far:

class AmmoRack < E extends Bullet, N > {

  AmmoRack<Bullet, Integer>[][] ammo;

  public AmmoRack() {
    this( {new Bullet(Bullet.AP), 50});// Bullet.AP is an int, public Bullet(int type){...}
  }
  public AmmoRack(AmmoRack<Bullet, Integer>[][] ammo) {
    this.ammo = ammo;
  }
}

I have looked at other questions, but they didn't seem to be particularly helpful for my case.

1 Answers

you can not define an array with two different types. bullet object is Bullet type and 50 is an Integer type. however all classes extends Object class.

if you write your code like this:

public class AmmoRack extends Bullet {

Bullet[][] ammo;

public AmmoRack(Integer anIntegerType, int n) {
    super(n);
    this.ammo = new Bullet[new Bullet(n)][anIntegerType];
}}

compile time error occurred and compiler says new Bullet(n) should be an int type.because you define an array! also Object[][] ammo; is wrong. same error will happen. unless you think a bullet is a number and define it on your Bullet class and that is illogical.

Related