exebook
exebook

Reputation: 33900

Store String+Integer pair in dynamic array?

I need to store few data pairs in array. Maybe few dozens. I only need to append, no need to delete, no need to search. Then I will access by index. Each pair is String value and Integer value. Java provides so many way to do this, which is the common practice for something like that? Two arrays? A class in an array?

I know how to do this in JavaScript:

var data = []
data.push(['Some name', 100])

//somewhere else
data.push(['Other name', 200])

but I need a solution for Java

Thank you.

Upvotes: 2

Views: 4602

Answers (3)

Harish Kumar
Harish Kumar

Reputation: 528

I go by using POJO as suggested above for this as this helps to define getter and setter for all the attributes of POJO, compare the objects by overriding equals and hashCode methods. By using getter and setter you know what is stored in what field and comparison can provide you sorting of objects as per your requirements. So this approach is cleaner and extensible for accommodating new requirements too. Also as you are putting data with sequential key so each instance of Pojo can be put in List (if required in sorted order.

Upvotes: 0

4ndrew
4ndrew

Reputation: 16252

For example you can create Pair class (or use implementations from apache commons) to store two elements in List.

List<Pair<String, Integer>> l = new ArrayList<>();
l.add(new Pair<String, Integer>("Some name", 100));

See Generic pair class and Java Pair<T,N> class implementation to see how you can implement Pair class.

Upvotes: 4

BobTheBuilder
BobTheBuilder

Reputation: 19294

It really depends, but in general I think it is better to create an object and use a list of it:

public class MyObject {
    private String myString;
    private Integer myInt;
    // getters setters
}

And use:

List<MyObject> = new ArrayList<>();

(you can also use Pair instead)

If the strings (or ints) are unique, you can use Map, but it is harder to get the insert index.

Another option is just two lists, one for Strings, one for Integers, and use same index in both lists.

Upvotes: 3

Related Questions