简体   繁体   中英

How to sort number from min to max number - Java?

How can i save numbers in List, where i could sort it from minimum to maximum. I created new string where i insert all numbers. Than i get in in List and sort it. After that i check a number and i get colour od icon.

I tried this:

import java.util.Collections;
import java.util.ArrayList;
import java.io.*;

int colour1 = 1;
int colour2 = 3;
int colour3 = 2;
int colour4 = 3;

String rezerva =colour1, colour2, colour3, colour4;
List<String> myList = new ArrayList(rezerva);
Collections.sort(myList);

colour1 = myList.get(0);

if (colour1==1){
//change icon to red
}
else if (colour1==2){
//change icon to white
}
else {
//change icon to black
}

Use Integer instead of String for your list

    Integer colour1=1;
    Integer colour2=3;
    Integer colour3=2;
    Integer colour4=3;

    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.add(colour1);
    myList.add(colour2);
    myList.add(colour3);
    myList.add(colour4);
    Collections.sort(myList);

You need to implement a comparator for your situation. And pass it as an argument to Collection.sort()

Not sure what you want... but to get your integers into the list, you can try:

List<Integer> myList = Arrays.asList(colour1, colour2, colour3, colour4);

Also at the top your colours are integers, but at the bottom they look like Strings, perhaps you can rephrase your question a bit. I think the solution will be easy.

save numbers in list: first of all the list should be from type int, then insert it one by one:

List<Integer> myList = new ArrayList<Integer>();
myList.add(colour1);
myList.add(colour2);
myList.add(colour3);
myList.add(colour4);

for sorting it just use:

Collections.sort(myList);

and it'll work because Integer implement Comparable

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