Possible to store string and integers in one object

12,483

Solution 1

Sure. You can put any members in an object you like. For example, this class stores a string and 11 integers. The integers are stored in an array. If you know there are going to be 11 of them (or any fixed number obviously) this tends to be preferable to storing 11 separate int members.

public class MyObject {
  private String text;
  private int[11] numbers = new int[11];

  public String getText() { return text; }
  public void setText(String text) { this.text = text; }
  public int getNumber(int index) { return numbers[index]; }
  public void setNumber(int index, int value) { numbers[index] = value; }
}

So you can write some code like:

MyObject ob = new MyObject();
ob.setText("Hello world");
ob.setNumber(7, 123);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(3));

Note: arrays in Java are zero-based. That means that a size 11 array has elements at indexes 0 through 10 inclusive.

You haven't really specified if 11 is a fixed number of what the meaning and usage of the numbers and text are. Depending on the answer that could completely change how best to do this.

Solution 2

Yes - make 12 private data members and you're there.

Whether they all belong in the same object is a different question.

Solution 3

You can put them in an array Objects as well:

private Object[] mixedObjs = new Object[12];
Share:
12,483
Alex
Author by

Alex

@alex_godin

Updated on July 31, 2022

Comments

  • Alex
    Alex almost 2 years

    Is it possible to store a string and 11 integers in the same object.

    Thanks,

    Alex