Home > Software engineering >  Is it possible to return an array of type <E> in a method in Java rather than an array of obje
Is it possible to return an array of type <E> in a method in Java rather than an array of obje

Time:02-15

I have a method that takes an in an array and copies it in a random order into another array and returns the shuffled array.

However, if I want to make it generic, I can't create the second array of type E. To get around this, I tried using an Arraylist and then using the .toArray() method and casting it to type E, but that returns an array of objects.

My current solution is to just modify the array directly and return that, but is there a way to return an array of the proper type, AKA the type of the array passed into the method?

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

public class ShuffleArray
{
    public static void main(String[] args)
    {
        String[] list = {"bob", "maryo", "john", "david", "harry"};
        
        //doesn't work, can't store array of objects in array of strings
        list = shuffle(list);
        
        //works because I modify directly
        shuffle(list);
        
    }

    public static <E> E[] shuffle(E[] list)
    {
        ArrayList<E> shuffledList = new ArrayList<>();

        //shuffle the array
        while (shuffledList.size() != list.length)
        {
            int randomIndex = (int)(Math.random() * list.length);
            if (!shuffledList.contains(list[randomIndex]))
            {
                shuffledList.add(list[randomIndex]);
            }
        }
        
        //overwrites the initial values of the array with the shuffled ones
        for (int i = 0; i < list.length; i  )
        {
            list[i] = shuffledList.get(i);
        }
        
        //How do I make this return an array of type String?
        return (E[]) shuffledList.toArray();
    }
}

CodePudding user response:

You have a different problem, better described here: make arrayList.toArray() return more specific types

Change your return statement to the following

return shuffledList.toArray(E[]::new);

CodePudding user response:

yeah why dont u just create an array of type E and store the values in it

E[] array = new E[list.length];

then just use that array to store the shuffled values and return it

  • Related