melar
melar

Reputation: 212

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 (please correct me if I got that wrong). But what I as a newbie want to do is to sort same values.

Say, I entered the values 3, 6, 4, 1, 2, 4, 7, 4 and I'm 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?

Upvotes: 0

Views: 634

Answers (1)

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;}

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

@Override
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");
System.out.println(ip1);

List<IntegerPlus> lipl=new ArrayList<IntegerPlus>();
lipl.add(ip1);
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)]

Collections.sort(lipl);

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 !

Upvotes: 2

Related Questions