Could someone please help me out with the following problem in java. I have a simple class defined as below:
public class Expr {
public long total_apparitions;
public String expression=new String();
public Expr(long total,String expr){
this.total_apparitions=total;
this.expression=expr;
}
public void increment(long aparitions){
total_apparitions+=aparitions;
}
}
I want to sort an array of Expr objects by the total_apparitions field, using the Arrays.sort built-in function. How do I specify to the Arrays.sort function the comparison factor? Thanks a lot.
As #Jason Braucht said, implement Comparable like this:
public class Expr implements Comparable {
...
public int compareTo(Object o) {
if(this.total_apparitions > ((Expr) o).total_apparitions)
return 1;
else if(this.total_apparitions < ((Expr) o).total_apparitions)
return -1;
return 0;
}
}
Make Expr implement java.lang.Comparable
Edit - Should have provided an example (others already did). Here's a full sample using generics.
public class Expr implements Comparable<Expr>
{
public long total_apparitions;
public String expression = new String();
public Expr(long total, String expr)
{
this.total_apparitions = total;
this.expression = expr;
}
public void increment(long aparitions)
{
total_apparitions += aparitions;
}
public int compareTo(Expr o)
{
if (total_apparitions > o.total_apparitions)
{
return 1;
}
else if (total_apparitions < o.total_apparitions)
{
return -1;
}
else
{
return 0;
}
}
}
As an alternative to implementing Comparable, you can pass a Comparator instance to the Arrays.sort() method. The advantage of doing it this way is that it allows you to have different concepts of sorting an array of objects of this type (say you might want to sort by the name later, in which case you just need a different implementation of the comparator).
For example:
public class ByApparationsComparator implements Comparator<Expr> {
public int compare(Expr first, Expr second) {
if (first.total_apparitions > second.total_apparitions) {
return 1;
} else if (first.total_apparitions < second.total_apparitions) {
return -1;
} else {
return 0;
}
}
}
Then you can say:
Arrays.sort(exprArray, new ByApparationsComparator());
Related
I have been assigned the problem: Write a generic WeightedElement<E,W> class which stores an
element of type E and a weight of type W. It should implement Comparable relying on W's compareTo(). You should enforce that W itself is comparable.
So far I have made the class and implemented comparable but am encountering issue when making the compareTo() method for W. I have:
public class WeightedElement<E, W extends Comparable<W>> {
public E element;
public W weight;
public WeightedElement() {
element = this.element;
weight = this.weight;
}
public int compareTo(W data) {
if (this.weight == data.weight) {
return 0;
} else if (this.weight < data.weight) {
return 1;
} else {
return 1;
}
}
}
I am encountering the issue that when I compare the weights, the weight for data is not found. Also are there any other methods I have to create to properly have a class that implements comparable on one of the variables? Thank you for any help
You have the generics right, but just like WeightedElement itself, you have to call compareTo on the weights -- you can't use < or == to do comparisons.
public class WeightedElement<E, W extends Comparable<W>> implements Comparable<WeightedElement<E, W>> {
private final E element;
private final W weight;
public WeightedElement(E element, W weight) {
this.element = element;
this.weight = Objects.requireNonNull(weight, "'weight' should not be null");
}
#Override
public int compareTo(WeightedElement<E, W> other) {
return other == null ? 1 : weight.compareTo(other.weight);
}
}
I need to sort a java list containing objects of type Hotel
List<Hotel> hotelList = new ArrayList<>();
Inside the class I do have the method
#Override
public List<Room> getAvailableRooms() {
return this.rooms;
}
I need to sort my hotelList by the price attribute found in Room class.
Any suggestions?
You should either use a Comparator or implement the Comparable interface
public class Foo implements Comparable<ToSort> {
private int val;
public Foo(int val){
this.val = val;
}
#Override
public int compareTo(ToSort f) {
if (val > f.val) {
return 1;
}
else if (val < f.val) {
return -1;
}
else {
return 0;
}
}
Read more here
https://dzone.com/articles/sorting-java-arraylist
I have a class called classes who has this compareto method:
#Override
public int compareTo(Object other) {
Cours ot = (Cours)other;
String heure2 = ot.heure;
int autre = Integer.parseInt(heure2.substring(0,2));
int le = Integer.parseInt(this.heure.substring(0,2));
if (autre > le) {
return 1;
}
if (autre == le) {
return 0;
} else {
return -1;
}
}
I have another class called day that has a list of classes :
private List<Cours> journee;
And a method to sort the classes:
public void TrieListe() {
Collections.sort(journee);
}
When I use TrieListe() everything works fine, I can sort the list.
But I've added another class called Weeks which contains a List of Days
And now I want to use TrieList() from that class :
private List<Days> leWeek;
public void TrieListe() {
Collections.sort(leWeek);
}
So how can I use my compareTo method from my classes class using sort() in my Weeks class.
Create a new abstract class AComparableByHour and make your classes extend it.
public abstract class AComparableByHour implements Comparable<AComparableByHour> {
public abstract String getHeure();
// Your comparison method goes here
#Override
public int compareTo(AComparableByHour ot) {
String heure2 = ot.getHeure();
int autre = Integer.parseInt(heure2.substring(0,2));
int le = Integer.parseInt(this.getHeure().substring(0,2));
if( autre > le){
return 1;
}
if( autre == le){
return 0;
} else {
return -1;
}
}
}
public class Cours extends AComparableByHour {
// This method is mandatory now.
// You could move it to the new superclass
public String getHeure() {
return heure;
}
...
}
public class Days extends AComparableByHour {
public String getHeure() {
return heure;
}
...
}
I have a class called classes who has this compareto method:
#Override
public int compareTo(Object other) {
This is already wrong. Your class should implement Comparable<classes> (noting that classes is a truly terrible name for a class, for at least three separate reasons), which will force the method signature to be:
#Override
public int compareTo(classes other) {
I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;
Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition ...
I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)
Help is appreciated!
Use Collections.sort() and specify a Comparator:
Collections.sort(friends,
new Comparator<FriendProfile>()
{
public int compare(FriendProfile o1,
FriendProfile o2)
{
if (o1.getUserPosition() ==
o2.getUserPosition())
{
return 0;
}
else if (o1.getUserPosition() <
o2.getUserPosition())
{
return -1;
}
return 1;
}
});
or have FriendProfile implement Comparable<FriendProfile>.
Implement Comparable Interface.
class FriendProfile implements Comparable<FriendProfile> {
private int userPosition;
#Override
public int compareTo(FriendProfile o) {
if(this.userPosition > o.userPosition){
return 1;
}
return 0;
}
}
Just Call the Collection.sort(List) method.
FriendProfile f1=new FriendProfile();
f1.userPosition=1;
FriendProfile f2=new FriendProfile();
f2.userPosition=2;
List<FriendProfile> list=new ArrayList<FriendProfile>();
list.add(f2);
list.add(f1);
Collections.sort(list);
The List will be sorted.
Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)
1)For Ascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1)For Deascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
Use Collections.Sort and write a custom Comparator that compares based on userPosition.
use Comparator with Collections.sort method
java.util.Collections.sort(list, new Comparator<FriendProfile >(){
public int compare(FriendProfile a, FriendProfile b){
if(a.getUserPosition() > b.getUserPosition()){
return 1;
}else if(a.getUserPosition() > b.getUserPosition()){
return -1;
}
return 0;
}
});
see this link
There are two ways to do this.
1.
FriendProfile could implement the interface Comparable.
public class FriendProfile implements Comparable<FriendProfile>
{
public int compareTo(FriendProfile that)
{
// Descending order
return that.userPosition - this.userPosition;
}
}
...
Collections.sort(friendProfiles);
2.
You could write a Comparator.
public class FriendProfileComparator implements Comparator<FriendProfile>
{
public int compare(FriendProfile fp1, FriendProfile fp2)
{
// Descending order
return fp2.userPosition - fp1.userPosition;
}
}
...
Collections.sort(friendProfiles, new FriendProfileComparator());
When comparing objects rather than primitives note that you can delegate on to the wrapper objects compareTo. e.g. return fp2.userPosition.compareTo(fp1.userPosition)
The first one is useful if the object has a natural order that you want to implement. Such as Integer implements for numeric order, String implements for alphabetical. The second is useful if you want different orders under different circumstances.
If you write a Comparator then you need to consider where to put it. Since it has no state you could write it as a Singleton, or a static method of FriendProfile.
You can use java.lang.Comparable interface if you want to sort in only One way.
But if you want to sort in more than one way, use java.util.Compartor interface.
eg:
The class whose objects are to be Sorted on its roll_nos
public class Timet {
String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getN() {
return roll_no;
}
public void setN(int n) {
this.roll_no = n;
}
public Timet(String name, int n) {
this.name = name;
this.roll_no = n;
}
public String toString(){
return this.getName();
}
}
The class for sorting:
public class SortClass {
public void go(){
ArrayList<Timet> arr = new ArrayList<Timet>();
arr.add(new Timet("vivek",5));
arr.add(new Timet("alexander",2));
arr.add(new Timet("catherine",15));
System.out.println("Before Sorting :"+arr);
Collections.sort(arr,new SortImp());
System.out.println("After Sorting :"+arr);
}
class SortImp implements Comparator<Timet>{
#Override
public int compare(Timet t1, Timet t2) {
return new Integer(t1.getN()).compareTo (new Integer((t2.getN())));
}
}
public static void main(String[] args){
SortClass s = new SortClass();
s.go();
}
}
I am trying to make a FIFO Queue that is filled with my own class object.
I found this example but if I replace < E > with < PCB > it does not work:
import java.util.LinkedList;
public class SimpleQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void put(E o) {
list.addLast(o);
}
public E get() {
if (list.isEmpty()) {
return null;
}
return list.removeFirst();
}
public Object[] getAll() {
Object[] res = new Object[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
list.clear();
return res;
}
public E peek() {
return list.getFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
public int size() {
return list.size();
}
}
E is a type parameter. In simple terms, you can consider it as a 'template' which can be used to create a queue that can hold instances of one particular class.
You can create a queue of your PCB objects as follows:
SimpleQueue<PCB> queue = new SimpleQueue<PCB>();
Java Generics FAQs is a good resource if you want to learn more about Java generics.
public class MyQueue{
int arr[]=new int[10];
int i=0;
int j=0;
public void inn(int a)
{
System.out.println("You hava entered :"+a);
arr[i]=a;
i=i+1;
}
public int out()
{
return arr[j++];
}
public static void main(String args[])
{
MyQueue q=new MyQueue();
q.inn(4);
q.inn(3);
q.inn(46);
q.inn(44);
q.inn(43);
System.out.println(q.out());
System.out.println(q.out());
System.out.println(q.out());
System.out.println(q.out());
}
}
The sun's generic tutorial says following:
We recommend that you use pithy
(single character if possible) yet
evocative names for formal type
parameters. It’s best to avoid lower 3
case characters in those names, making
it easy to distinguish formal type
parameters from ordinary classes and
interfaces. Many container types use
E, for element, as in the examples
above.
So, it can't be the problem that you changed it to PCB.
But if PCB is the only class of which you want to store objects, you don't have to create a generic class. Just remove <PCB> from your class definition line and replace all E's with PCB:
public class SimpleQueue
{
LinkedList<PCB> list = new LinkedList<PCB>();
....
public PCB peek()
{
return list.getFist();
}
}