melar melar - 3 months ago 19x
Java Question

How to make a priority int list that regards the insertion order in case of duplicates in Java?

i want to make a priority list entering int values. i know that the list would normally have an ascending natural order (pls correct me if i got that wrong). but what i as a newbie wanna do and fail to do is to sort same values. Say, i entered the values 3, 6, 4, 1, 2, 4, 7, 4 and im expecting a list of ascending int values. but i want in the above list the second 4 to have lower priority, hence i want it coming right after the first 4 value and the third 4 value after the second etc... are there any classes /methods in java for that? where should i look for tips? thx for your patience


1 if you want to distinguish between 4 and 4, you have to add something => make a class

2 not to reinvent the wheel, use Collections (which accept duplicates) and sort

3 then you have to implement some comparison (implements Comparable)

see this: How to sort an ArrayList in Java

it gives this:

// It is like Integer + !

public class IntegerPlus implements Comparable<IntegerPlus>
int value=0;
String id="";

public IntegerPlus(int _val) {value=_val;}
public IntegerPlus(int _val, String _id) {value=_val; id=_id;}

public String toString() {return value+"("+id+")";}

public int compareTo(IntegerPlus _other)
    if (value>_other.value) return 1;
    if (value<_other.value) return -1;
    return 0;


4 good luck: you can use a regular sort: it preserves initial order on duplicates:

see this post: Does Collections.sort keep order on equal elements?

it gives:

IntegerPlus ip1=new IntegerPlus(4,"first");

List<IntegerPlus> lipl=new ArrayList<IntegerPlus>();
lipl.add(new IntegerPlus(2,"b"));
lipl.add(new IntegerPlus(4,"second"));
lipl.add(new IntegerPlus(1));
lipl.add(new IntegerPlus(3));
lipl.add(new IntegerPlus(5));
lipl.add(new IntegerPlus(6));
lipl.add(new IntegerPlus(4,"third"));
lipl.add(new IntegerPlus(2,"c"));

System.out.println("BEFORE SORT:"+lipl);

=> BEFORE SORT:[4(first), 2(b), 4(second), 1(), 3(), 5(), 6(), 4(third), 2(c)]


System.out.println("AFTER SORT:"+lipl);

=> AFTER SORT:[1(), 2(b), 2(c), 3(), 4(first), 4(second), 4(third), 5(), 6()]

hope it helps !