Lea2501
Lea2501

Reputation: 351

Array with 2 values per item

I'm trying to make an array with 2 values per item, like a value with a custom header, and, coming from Ruby, can't find a correct way to do this in Java.

This is for a REST-assured tests that i need to automate.

This is the method that i need to do, I mix the declaration of obj with some sort of ruby way to do it, so the necessity it's more clear:

private String[] getHeaders() {
    String[] obj = [
           'Signature' => this.getSignature(),
           'Timestamp' => this.getTimestamp(),
            ];

        if(getSessionToken() != null) {
            obj.sessionToken = this.getSessionToken();
        }
    }
}

Upvotes: 0

Views: 4222

Answers (2)

Janice Kartika
Janice Kartika

Reputation: 502

You can achieve that by creating a model. For example:

public class MyModel {
    private String signature;
    private String timestamp;

    public MyModel() {
        // constructor
    }

    public MyModel(String signature, String timestamp){
        this.signature = signature;
        this.timestamp = timestamp;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }
}

Then create an array of your model. You can use:

private static final int MODEL_SIZE = 5;
private MyModel[] models = new MyModel[MODEL_SIZE];

if you already know the size of your array. Or you can use this approach below if you don't know the size of array yet:

private ArrayList<MyModel> models = new ArrayList<>;
private MyModel model;

// Then fill your models

// by using this way
model = new MyModel("My Signature", "My Timestamp");
models.add(model);

// or this way
model = new MyModel();
model.setSignature("My Signature");
model.setTimestamp("My Timestamp");
models.add(model);

Another way to achieve that without creating a model is by using HashMap. This is the example:

List<HashMap<String, String>> objects = new ArrayList<>();

HashMap<String, String> object = new HashMap<>();
object.put("signature", "My Signature");
object.put("timestamp", "My Timestamp");

objects.add(object);

Upvotes: 3

EngineerExtraordinaire
EngineerExtraordinaire

Reputation: 119

Something like this I suspect is what you want.

   class Headers{
         public String signature;
         public String timeStamp;
    }
    Headers[] header = new Headers[10];

You probably don't need getters and setters, but you can throw those in too.

Upvotes: 1

Related Questions