开发者

Possible to store string and integers in one object

开发者 https://www.devze.com 2022-12-14 18:48 出处:网络
Is it possible to store a string and 11 integers in the same object. 开发者_运维知识库Thanks, AlexSure. You can put any members in an object you like. For example, this class stores a string and 11

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

开发者_运维知识库

Thanks,

Alex


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.


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

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


You can put them in an array Objects as well:

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


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


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消