简体   繁体   中英

Generating random numbers and sorting them out in Java

My goal is to generate random number from 0 to 100 and add them into a linkedlist object and then sort the elements.

This is my code so far. I'm running into problems when I want to display the sorted elements.

The error I get: Exception in thread "main" java.util.IllegalFormatConversionException: d != java.util.Arrays$ArrayList

Can someone throw some light into this problem? Thank You

package com.LinkedLists;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;

public class InsertRandomElements {

    public static void main(String[] args) {

        // Create a random number object from 0 to 100.
        // Create an array object.
        Random r = new Random();
        int[] random = new int[100];

        // Insert random numbers into the array
        for (int i = 0; i < random.length; i++) {
            random[i] = r.nextInt(100) + 1;
        }

        // Printing out the unsorted array
        for (int i = 0; i < random.length; i++) {
            System.out.println(random[i]);
        }

        List<int[]> randomList = Arrays.asList(random);

        // Call the method in here.
        sortElements(randomList);

    }

    // Sort the elements
    private static void sortElements(Collection<int[]> values) {

        Set<int[]> set = new HashSet<int[]>(values);

        for (int[] is : set) {
            System.out.printf("Sorted Elements: %d ", values);
        }

        System.out.println();
    }

    // Calculate Sum of the elements

    // Calculate floating point average of the elements.

}

You need a List<Integer> and not a List<int[]> . Converting from a primitive array into a list of Integers is not a one-call operation, you'll actuall have to iterate over the primitive array and add to the list one by one. I don't recommend this, especially since there is no reason to use the array in the first place. For reference, you need this:

final List<Integer> randomList = new LinkedList<>();
for (int i : random) randomList.add(i);

When you change that, this will work:

System.out.printf("Sorted Elements: %s ", values);

However, it would be much simpler to sort the array itself using Arrays.sort(myArray) and then print using

System.out.println(Arrays.toString(myArray));

On the other hand, if you used a List<Integer> right from the start, it would look like this:

final Random rnd = new Random();
final List<Integer> values = new ArrayList<>();
for (int i = 0; i < 100; i++) values.add(rnd.nextInt());
Collections.sort(values);
System.out.println("Sorted Elements: " + values);

Its getting confused because ** int[] is an object but int is not so it assumes int[] as one element of the List , and hence returning List<int[]> not List<Integer> or List<int>(this is not possible and is causing the issue) .

Please change your random to Integer[] as below, it should work fine.

    Integer [] random = new Integer[100];
    List<Integer> randomList = Arrays.asList(random);

To sort the list: Use Collections#sort

    Collections.sort(randomList);

Please remember , the method signature is: public static <T> List<T> asList(T... a) which determines the type of List to be returned based on the argument type being passed.

Please Note: Even when you define random as new Integer[100]; , still you can leave this kind statements as is: random[i] = r.nextInt(100) + 1; . This works fine as int is promoted to Integer in those cases.

In this case, I think it would be easier to pass the random array directly to a sortElements(int[] values) method and then convert the array to a list.

In other words, you would call sortElements(random); and then List<Integer> randomList = new LinkedList(Arrays.asList(random)); to get a linked list.

Using your code try:

for (int[] is : set) {
   System.out.printf("Sorted Elements: %d ", is[0]);
}

but you still need to sort it, as mentioned in previous post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM