0

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!

10
  • 4
    Vector is deprecated.. You would better go with ArrayList.. Apart, can you show some code you might have tried?? Commented Sep 27, 2012 at 17:52
  • 2
    Use ArrayList<Pair> instead. Pair is a class you define which has 2 fields. Commented Sep 27, 2012 at 17:53
  • 4
    Or, even better, don't use Pair -- write a class that actually describes what the two strings actually mean. Commented Sep 27, 2012 at 17:54
  • 1
    I think someone should point out that Vector is deprecated in favor of ArrayList. Commented Sep 27, 2012 at 18:00
  • 1
    @RohitJain It's not deprecated, it's just no longer considered good practice to use due to the unnecessary overhead from the fact that it pretends to be thread safe with synchronized methods. It works, and it's not going to be removed in any future releases (the definition of deprecated is that it may be removed in the future), its use is just an indication of "immature code" (in the words of IDE hints). Commented Sep 27, 2012 at 18:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Apache commons provides a nice Pair class to store two values. Using an array of size 2 would look a bit hacky.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.