Hello

Is there anyway to move a string array elements to a vector and have an output that list these elements?

Let's say the array contains the following elements

String arraySize[] = {"A", "B", "C", "D", "E"};

and I want to move these elements to a vector.. How would I do it? Oh and I have to use array.Length to get the size

And this is what I am planning to do

for (int Counter =0; Counter < Arraysize.Length; counter ++)
{
  VectorName.add(arraySize);   
}

It won't work though.. It will through an exception.

I will really appreciate your help if you help me.

Recommended Answers

All 11 Replies

What exactly do you mean by vector? Do you mean the Vector class?

ArrayList is much more common nowadays, prefer that container class over Vector.

As stated in the API:

This class is roughly equivalent to Vector, except that it is unsynchronized.

Also you don't need a loop, you can use the Arrays utility class.

Here's how:

String[] sArr = {"A", "B", "C", "D", "E"};
List<String> list = Arrays.asList(sArr);

However the asList() method will return a fixed-size list that is backed by the array you pass in as the argument, this means that you cannot structurally modify [1] the returned list.
If this behaviour is required, you use it in conjunction with one of the ArrayList constructors that take in a Collection.

Here's how:

String[] sArr = {"A", "B", "C", "D", "E"};
List<String> list = new ArrayList<String>(Arrays.asList(sArr));

However if you want to do it manually using a loop, here are two ways:

Using a counter-controlled for loop:

String[] sArr = {"A", "B", "C", "D", "E"};
List<String> list = new ArrayList<String>();

for (int i = 0; i < sArr.length; i++)
    list.add(sArr[i]);

Using an enhanced for loop:

String[] sArr = {"A", "B", "C", "D", "E"};
List<String> list = new ArrayList<String>();

for (String s : sArr)
    list.add(s);

It won't work though.. It will through an exception.

As for your problem, you probably didn't initialize your reference to refer to an ArrayList (or something equivalent).
If you still encounter problems, then it would be helpful if you'd post the stacktrace you get.

[1] A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification. (Java API)

I can't use arrayList in this lab.. I am trying to use the normal arrays for now.

Is there anyway to move a string array elements to a vector and have an output that list these elements?

Let me ask again: What do you mean by vector?
Also please post the smallest compilable piece of code that demonstrates your problem with the exception.

by Vector, I'm pretty sure he means : Vector.
when you iterate over your array, extract the elements one by one and add those to the vector.

by Vector, I'm pretty sure he means : Vector.
when you iterate over your array, extract the elements one by one and add those to the vector.

Well, in that case my suggestions would still work. Since Vector implements the List interface as of Java 1.2, and since it has a constructor that takes in a Collection, the only thing (s)he needs to do is replace the ArrayList constructor calls by Vector constructor calls.

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. (Java API - Vector)

Yes I meant Vector and there are certain things I can use in this program.. I am limited to use an array and a Vector.. I know multiple ways to do it without how the teacher wants it but this is all what I got.. I can post the whole code if you want me to..

Simplest code is probably

      String[] a = {"a","b","c"};
      Vector<String> v = new Vector<>(Arrays.asList(a));

Edit: oops - I missed the fact hat tux4life had already covered this - sorry for the duplication. J

commented: Exactly :) +13

Here is the code I am writing.. Instead of trying to explain it million times.

public class VectorDemo {

    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub

        String[] courseName ={"Java Development", "JAVA5203", "College", "City", "User Name"};

        Vector firstCourseDetail = new Vector();
        Vector secondCourseDetail = new Vector(4);


        int firstCount = firstCourseDetail.capacity();
        int firstCountSize = firstCourseDetail.size();

        int secondCount = secondCourseDetail.capacity();
        int secondCountSize = secondCourseDetail.capacity();

         for(int counter=0; counter< courseName.length ; counter++) // inner loop counts for 4 and stops at 3

         {

            firstCourseDetail.add(courseName); 


        }


        for(int counter=0; counter< courseName.length ; counter++)
        {

            secondCourseDetail.add(courseName); 

        }


        System.out.print("The capacity of the first vector is " + firstCount + " And the size of it is " + firstCountSize);
        System.out.print("\nThe capacity of the second verctor is " + secondCount + " and the size of it is " + secondCountSize);
        System.out.print("\nThe content is: " + firstCourseDetail);
        System.out.print("\nThe content of the second vector is " +secondCourseDetail);




    }

}

See how I am trying to store it? It have to be based on a for loop the instructor said we have to do it this way.

Now, this is an excellent example of why you should use type parameters: you are adding the array to your Vector instead of a String, and Java will happily allow it, since you are using a raw type.
Your compiler should've given you a warning about this.
As illustrated by your code you should NEVER ignore a compiler warning without having a good reason for doing so.

This is the compiler output you get when you declare without type parameters:

Note: VectorDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Your declaration without type parameters looks like this:

Vector firstCourseDetail = new Vector();
Vector secondCourseDetail = new Vector(4);

Compiling with -Xlint:unchecked gives the following warnings:

VectorDemo.java:28: warning: [unchecked] unchecked call to add(E) as a member of
 the raw type Vector
            firstCourseDetail.add(courseName[counter]);
                                 ^
  where E is a type-variable:
    E extends Object declared in class Vector
VectorDemo.java:37: warning: [unchecked] unchecked call to add(E) as a member of
 the raw type Vector
            secondCourseDetail.add(courseName);
                                  ^
  where E is a type-variable:
    E extends Object declared in class Vector
2 warnings

The compiler is informing you here that it cannot guarantee you that the arguments you pass to the add() method will always be of the same type.
They could literally be everything that is an Object, and in Java every class conforms to the is an Object rule.
And that is what happened in your code. In Java an array is an Object.

If you use type parameters, then the compiler can check and ensure that you're only adding elements that are of the same type.

Here's how you declare your Vectors using a type parameter:

Vector<String> firstCourseDetail = new Vector<String>();
Vector<String> secondCourseDetail = new Vector<String>(4);

After recompiling now, you'll get the following compiler errors:

VectorDemo.java:28: error: no suitable method found for add(String[])
            firstCourseDetail.add(courseName);
                             ^
    method Vector.add(int,String) is not applicable
      (actual and formal argument lists differ in length)
    method Vector.add(String) is not applicable
      (actual argument String[] cannot be converted to String by method invocation conversion)

VectorDemo.java:37: error: no suitable method found for add(String[])
            secondCourseDetail.add(courseName);
                              ^
    method Vector.add(int,String) is not applicable
      (actual and formal argument lists differ in length)
    method Vector.add(String) is not applicable
      (actual argument String[] cannot be converted to String by method invocation conversion)
2 errors

Don't worry, this is actually a good thing, the compiler is helping you here because it is telling you that you made a mistake.
In this case the mistake is that you are adding the whole array multiple times to the Vector, instead of adding the elements in the array.

You can fix it as follows:

for (int counter = 0; counter < courseName.length; counter++)
{
    firstCourseDetail.add(courseName[counter]);  // use counter as array index!
    secondCourseDetail.add(courseName[counter]); // use counter as array index!
}

Also notice that I replaced the two loops by one.

Furthermore I don't see any reason why you'd need to use Vector nowadays, and that is probably because there really is no reason. Ask your lecturer, can he give a good reason? Perhaps in very exceptional circumstances you'd need to use Vector. But nowadays the Vector class is considered legacy, and it is also slower than it's ArrayList counterpart because of the synchronization which you don't need in most cases.

It would also be a good idea to concisely choose your variable names, e.g. courseNames would be more appropriate for an array since it clearly indicates that there is more than one occurence, whereas courseName (without s) could imply that you're dealing with a variable declared as of type String.

So a tip for the future: if you are free to choose between Vector and ArrayList, then you should choose ArrayList (unless you have a very good reason not to do so), and use the Arrays utility class as described in one of my previous posts. It is a correct, more compact, more recent and more productive way to achieve the same.

For more info refer to the following links:

  1. Vector versus ArrayList
  2. Why Vector is considered obsolete
commented: You sir deserve more likes.. That was the answer I wanted.. Some explanation of what's going on.. And I believe you are right, Vectors are rarely used.. But you know Instructors. +0

I don't see any reason why you'd need to use Vector nowaday

In general yes. The only one I know is some Swing components (eg Jist, JTable) have convenient constructors that accept Vectors of data but not ArrayLists (they really should have been updated to accept Lists, but hey ho).

In general yes. The only one I know is some Swing components (eg Jist, JTable) have convenient constructors that accept Vectors of data but not ArrayLists (they really should have been updated to accept Lists, but hey ho).

True. But even then you could work around it by applying the Adapter design pattern and writing a ListModel implementation with a constructor that accepts a List.
No doubt that there's some work involved in that, but once written you can reuse it :)

commented: I agree with you guys.. Reusing the same functions or the constructors reduce the load on memory, and I know that most of modern devices have a lot of memory but when it comes to mobile devices we still need to pay attention to how much memory the process +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.