Change class vector size

Asked

Viewed 202 times

1

I have to use vector public static String vetor[] = new String [15]; in the class... but this class is used in a Servlet. And the size I need the vector is what the user chooses... how can I pass the parameter that defines the vector size. I know this 15 is only representative... I need a variable, but how to declare a class vector using a variable that comes from Servlet?

2 answers

5


You can solve this by instantiating the vector in the class constructor and taking the size as argument:

public class Teste
{
   public static String vetor[];
   ...
   public Teste(int tamanhoVetor)
   {
       vetor = new String [tamanhoVetor];
   }
}

In the Servlet could be something like (the way you take the value can be different):

...
Teste testando = new Teste(Integer.valueOf(request.getAttribute("txtTamanho").toString()));
...

1

I don’t know if you’re working with JSP, but if you are, you need to use Request for this

   request.setAttribute("key", "valor") //set uma variavel de request

   RequestDispatcher rd = request.getRequestDispatcher("/teste.jsp"); 
   rd.forward(request, response);

   String valor = (String) request.getAttribute("key"); //pega o request na sua classe jsp

   String meuArray[] = new String[valor]; //Set o valor passado no seu Array =)
  • this I already do... my problem is only in the vector(array) part of Java

  • You just pick up & #Xa; String valor = (String) request.getAttribute("key");
String meuArray = new String[valor];

  • Edit your answer, so I withdraw the negative vote... are the standards.

  • 1

    I edited, I was not very clear in the reply, I’m sorry, I hope I helped =D

  • Still the meuArray not an array, fix ai @Danilooliveira. :)

  • 1

    Okay, what a lack of attention from me...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.