Alex
Alex

Reputation: 730

Possible to store string and integers in one object

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

Thanks,

Alex

Upvotes: 2

Views: 16533

Answers (5)

larsaars
larsaars

Reputation: 2350

Create a class that implements an object containing a string and 11 integers:

public class StringAndInt extends Object
{
    private int[] user = new int[11];
    private String string = "";

    public StringAndInt(String s, int[] i){
        user = i;
        string = s;
    }
    public StringAndInt setInt(int[] i){
        number = i;
        return this;
    }
    public StringAndInt setString(String s){
        string = s;
        return this;
    }
    public int getInt(){
        return user;
    }
    public String getString(){
        return string;
    }
}

Upvotes: 0

fastcodejava
fastcodejava

Reputation: 41097

You can put them in an array Objects as well:

private Object[] mixedObjs = new Object[12];

Upvotes: 1

cletus
cletus

Reputation: 625077

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.

Upvotes: 17

just_wes
just_wes

Reputation: 1318

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

Upvotes: 0

duffymo
duffymo

Reputation: 308763

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

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

Upvotes: 2

Related Questions