Mohammed Irfan
Mohammed Irfan

Reputation: 93

Matching of the Parameters in Vectors

I am trying to Learn Java as I am a beginner and recently i fumbled upon Vectors and Lists in Java. This is a very simple and a basic question, but any help would be really helpful for a learner. I have created a vector v as shown below:

public vector createVector(){
    Vector v = new Vector();
    v.add(Path1);   //Path1 is the path of a directory
    v.add(Path2);
    return v;
}

I have a function in which I pass, one of the parameter is v.get(i). The function is shown below:

for(int i=0,i<v.size(),i++){
    qlm("Write", "init",getList(),**v.get(i)**); // Function call. 
}

Function declaration is :

Void qlm(String Option, String init, List lists, **String paths**){

}

I am not able to match the parameter in the function call which is v.get(i) with String Paths. Please share your knowledge.

Thanks a lot.

Upvotes: 0

Views: 275

Answers (3)

TwentyMiles
TwentyMiles

Reputation: 4089

Typically, in Java, when somebody declares a Vector they will declare it using Generics. To declare a Vector that will contain strings, you would write this:

Vector<String> myVector = new Vector<String>();

Then, to get a iterate over it's values, you would do this:

for(int i = 0; i < myVector.size(); i++){
    String s = myVector.get(i); // The get() method here returns a String instead of Object
}

Or, because Vectors are enumerable, you could do this:

for(String s : myVector){
    // There is now a variable named s available in the loop that
    // will contain each element in the vector in turn. 
}

That being said, you really shouldn't use Vectors any more. They are pretty old, and there are better lists available in Java. I would recommend that you use an ArrayList, but they're a variety of lists available which can be found here under "All known implementing classes."

To rewrite your example using generics and an ArrayList, you would do this:

List<String> myList = new ArrayList<String>();
myList.add(Path1);
myList.add(Path2);

for(String s : myList){
    qlm("Write", "init", getList(), s);
}

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30809

Without Generics, v.get(i) will always return an object. Here are two ways to resolve it:

Declare Vector as

Vector< String > v = new Vector< String > ();

Or do

v.get(i).toString();

But before doing v.get(i).toString(), null check should be performed on v.get(i).

Upvotes: 2

shreyansh jogi
shreyansh jogi

Reputation: 2102

try this

for(int i=0,i<v.size(),i++){
    qlm("Write", "init",getList(),v.get(i).toString()); // Function call. 
    }

Upvotes: 0

Related Questions