Is there a more elegant way to handle lists in Java? (Python VS Java)

I like the way Python handles lists It makes any recursive solution look easy and clean For example, the typical problem of getting all permutations of elements in Python is as follows:

def permutation_recursion(numbers,sol):
    if not numbers:
        print "this is a permutation",sol
    for i in range(len(numbers)):
        permutation_recursion(numbers[:i] + numbers[i+1:],sol + [numbers[i]])

def get_permutations(numbers):
    permutation_recursion(numbers,list())

if __name__ == "__main__":
    get_permutations([1,2,3])

I like to simply get a new instance of the modification list in this way: number [: I] number [I 1:] or sol [number [i]]

If I try to write exactly the same code in Java, it looks like:

import java.util.ArrayList;
import java.util.Arrays;

class rec {
    static void permutation_recursion(ArrayList<Integer> numbers,ArrayList<Integer> sol) {
       if (numbers.size() == 0)
            System.out.println("permutation="+Arrays.toString(sol.toArray()));
       for(int i=0;i<numbers.size();i++) {
             int n = numbers.get(i);

             ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
             remaining.remove(i);

             ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
             sol_rec.add(n);

             permutation_recursion(remaining,sol_rec);
       }
    }
    static void get_permutation(ArrayList<Integer> numbers) {
        permutation_recursion(numbers,new ArrayList<Integer>());
    }
    public static void main(String args[]) {
        Integer[] numbers = {1,3};
        get_permutation(new ArrayList<Integer>(Arrays.asList(numbers)));
    }
}

To create the same recursion, I need to do the following:

ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
remaining.remove(i);

ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
sol_rec.add(n);

This is very ugly and worse for more complex solutions Like in this example

So my question is... Are there any built-in operators or helper functions in the Java API that can make this solution more "Python"?

Solution

No,

But that's why Martin odersky created Scala He even said that one of his goals for Scala was that it was Python in the Java world Scala is compiled into Java bytecode and can easily interact with Java compiled classes

If this is not an option, you can see the Commons collection library

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>