Reputation: 6040
i am interested in using a String array as an element in a Vector object. The array will always be of length 2. Is there a better way for this data structure? Reason for using the Vector is because of dynamic resizing, ie the number of elements vary and i would like to use the add
and trimToSize
methods for Vector.
Thanks!
Upvotes: 0
Views: 86
Reputation: 17309
Use ArrayList
and a custom object instead.
public class MyStrings {
private String string1;
private String string2;
public MyStrings(String string1, String string2) {
this.string1 = string1;
this.string2 = string2;
}
public String getString1() {
return string1;
}
public String getString2() {
return string2;
}
}
Then to use it:
List<MyStrings> list = new ArrayList<MyStrings>();
list.add(new MyString("apple", "orange");
// To iterate:
for (MyStrings myStrings : list) {
System.out.println(myStrings.getString1());
System.out.println(myStrings.getString2());
}
Vector
is no longer considered a good dynamic array in Java because of extra synchronization logic that's more or less useless, so it just adds unnecessary overhead. ArrayList
is the go-to dynamic array. You could also use LinkedList
, which is a doubly-linked list.
Of course, you should also use better naming conventions that describe what the values actually mean instead of the names that I used in my example.
Upvotes: 1
Reputation: 24124
Apache commons provides a nice Pair class to store two values. Using an array of size 2 would look a bit hacky.
Upvotes: 0