views:

154

answers:

4

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

Thanks,

Alex

+2  A: 

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

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

duffymo
A: 

Yes. You will have to create this class. It is possible.

just_wes
+15  A: 

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.

cletus
That's 12 numbers :P
Josh Stodola
int x[5] is 5 numbers so it isnt 12.
JonH
@Josh Stodola, no offense, but what are you talking about? Initializing an `int` array with `new int[11]` definitely only holds 11 int primitives, since it's the constructor, not the reference to one of the array's positions. And cletus didn't use a varargs-type method or constructor, so all in all, I'm confused by your two comments.
delfuego
@delf: the ... Josh is referring to was what I had in place of the methods of the class as a form of abbreviation (see the history).
cletus
+2  A: 

You can put them in an array Objects as well:

private Object[] mixedObjs = new Object[12];
fastcodejava
Autoboxing is evil.
bmargulies
He doesn't need to use autoboxing to put ints into an Object[].
Stephen C