C
C
Caffeinee2020-02-21 16:41:00
Java
Caffeinee, 2020-02-21 16:41:00

How to pass an array from a java method and why clear it?

I take user nicknames with a certain value from the site database and replace the value so that I no longer take the same nicknames. I put them in an array and pass it through return to the main class. And after the transfer, I need to clear the array so that next time I don’t transfer the same nicknames again. For the test, I wrote this, but it just produces a list of null.

public class sql {
  public static String[] get_names() {
    
  String[] name = new String[] {"caf","caf1","caf2","caf3"};
  String[] name_return = name;
 for(int i =0; i < name.length; i++) {
      name[i] = null; }
  return name_return;}}
How can I pass an array from a method and then clear it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2020-02-21
@Caffeinee

First, there is no concept of "clearing" an elementary array in java. But it is possible to clear a list of type List (Vector, Arralist, etc.).
Secondly, I don’t understand why you need to clean something at all, in Java there is an excellent automatic garbage collector, which we are all proud of.
Thirdly, it is necessary to pass an array in the right way, simply returning its name in return

W
WerkEng, 2020-02-22
@WerkEng

In your example, everything inside the get_names method will be deleted after it is executed (including the array you create and return there). And this will happen every time you call this method.
To constantly keep an array and work with it, you need to declare this array somewhere (for example, in the Sql class), and you only have a method there.
And as already mentioned above, an array is not the best solution in this case, because it is created with a certain size, and then you can no longer change this size. Use a List instead of an array. Then it will be possible to resize, fill and "clear" the content.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question