forsb
forsb

Reputation: 135

Is there a way to remove an object from a Method[]

Im a bit new to java and can't seem to find a good solution to my issue. I load in a Class and have a set of rules that I want to compare each method of that class to.

for(Method methods : methods){
     if(checkMethod(methods)){
         //Method is approved
      }
      else{
         //Method is not approved  
      }
}

My issue here is that I want to either remove that method from the already existing array of methods or add the approved methods to a new array and save them separately. It seems like the Method[] is not capable of removing objects in its array? And when creating a second array and then using something like:

if(checkMethod(methods)){
   approvedMethods[i] = methods;
}

it feels like im doing something wrong, the second array won't contain any of the approved methods. Is it possible to delete an object from the original array or is the correct way to create a second one, if that is the case how do i correctly add them to the new array? Cant seem to find a approvedMethods.put()/add().

There is nothing wrong with the method checkMethod(), tested it with multiple cases and gives out the exepected output.

Upvotes: 3

Views: 84

Answers (1)

dreamcrash
dreamcrash

Reputation: 51423

Just do like:

Method[] collect = Arrays.stream(array)
                         .filter(AccessibleObject::isAccessible)
                         .toArray(Method[]::new);

Go through the array methods, filter the desirable methods, and return them into a new array.

In Java, you cannot remove from an array using remove a-like methods. For that kind of functionality use an ArrayList instead.

If you want to use only arrays, then you would have to do something like:

First, find out the number of accepted methods so that you know beforehand how much space you will need to allocate for the array:

int count = 0;
for(Method method : methods){
     if(checkMethod(methods)){
        count++;
      }
}

Then allocate the space for that array:

Method[] approvedMethods = new Method[count];

now add the methods that fits your constraints:

int i = 0;
for(Method method : methods){
     if(checkMethod(methods)){
        approvedMethods[i++] = method
      }
}

One of the downsides of such an approach is that it goes through the array twice.

Upvotes: 4

Related Questions