-11

I need to convert the array to an array list and am not sure how to do this, I have looked at other articles on here and couldn't seem to get it to work, if anyone could provide me with some pointers as and to how to convert this to an array list that would be fab.

 import java.util.*;

 public class SearchExamResults
 {
    public static void main(String[] args)
    {
        Result[] resultsArray = new Result[20];

        input(resultsArray);
        sortByMark(resultsArray);
        output(resultsArray);
    }

    public static void input(Result[] array)
    {
        Scanner kybd = new Scanner(System.in);
        for (int i = 0; i < array.length; i++)
        {
            System.out.println("Candidate " + (i + 1));
            System.out.print("\tName: ");
            String name = kybd.nextLine();
            System.out.print("\tMark: ");
            int mark = kybd.nextInt();
            kybd.nextLine();            //to flush the kybd buffer

            array[i] = new Result(name, mark);
        }
    }

    public static void sortByMark(Result[] array)
    {
        //selection sort
        for (int pass = 1; pass < array.length; pass++)
        {
            int lastElement = array.length - pass;
            int largePos = findLargestMark(array, array.length - pass);
            if (largePos != array.length - pass)
            {
                Result temp = array[largePos];
                array[largePos] = array[lastElement];
                array[lastElement] = temp;
            }
            //this is for testing purposes only
            //output(arr); 
        }
    }

    public static int findLargestMark(Result[] array, int last)
    {
        int largestPos = 0;
        for (int i = 1; i <= last; i++)
        {
            if (array[i].getMark() > array[largestPos].getMark())
            {
                largestPos = i;
            }
        }
        return largestPos;
    }

    public static void output(Result[] array)
    {
        System.out.println("\nExam results");
        System.out.println("============");

        for (int i = 0; i < array.length; i++)
        {
            System.out.printf("\t%-20s\t%d\n", array[i].getName(), array[i].getMark());
        }
    }
 }
nitishagar
  • 9,038
  • 3
  • 28
  • 40

1 Answers1

1

You can use Arrays.asList(T...) or you can do it your own by iterating through all Elements like this:

ArrayList<Result> list = new ArrayList<Result>();
for(Result r : resultsArray) {
    list.add(r);
}

PS: you can use the search function to see if this has been asked before.

tobs
  • 699
  • 2
  • 8
  • 24