Why cant I use toString() with vector?
I have declared a new vector called v of type String with an initial capacity of 10 and increasing by 5 each tiem using the following:
Code :
Vector<String> v = new Vector<String>(10, 5);
I am then trying to use the add method to add a randome string as follows:
Code :
v.add(toString(random.nextInt(5000)));
I am getting the following error;
Code :
error: method toString in class Object cannot be applied to given types;
Why can't i do this? I would have thought it would just pass a random number as a String!
Re: Why cant I use toString() with vector?
See the API for Object - the toString method contains no parameters and returns a String - you are attempting to call a toString(int val) method, which does not exist. Call toString on an object, not passing the object to the method:
Code :
Integer i = new Integer(random.nextInt(5000));//without autoboxing for clarity
String stringValue = i.toString();
Re: Why cant I use toString() with vector?
That is not how toString works. You have to call the method on an object and you do not pass it a parameter.
Code java:
class Foo {
String name;
String dob;
Foo(String n, String d) {
name = n;
dob = d;
}
public String toString() {
return name + " was born on " + dob;
}
public static vodi main(String[] args) {
Foo f = new Foo ("Bob", "1/4/1950");
System.out.println(f.toString());
// or
System.out.println(f); //toString method is automagically called
}
}
Re: Why cant I use toString() with vector?
Fantastic, that will be why it wasn't working then!
Thanks
Re: Why cant I use toString() with vector?
Your program has some error i.e
nextInt() is not a static method.we cant call it directly with class name .
Try It.
Random r=new Random();
Vector<String> v = new Vector<String>(10, 5);
v.add(Integer.toString(r.nextInt(5000)));