This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 4 years ago.
So I've made an ArrayList of Catalogue Entries, where CatalogueEntry is made up of an int, a string and a status (which has been previously defined). I want to order the elements of the list (aka the Catalogue Entries) according to their integer. Is there any way I can do this?
Yes there is, but you must tell the program what do you mean by saying that one CatalogueEntry is bigger then an other. There are multiple ways of doing this but one example is the Comparable interface
public class CatalogueEntry implements Comaparable<CatalogueEntry> {
private int yourInt;
//methods, variables here
#Override
public int compareTo(CatalogueEntry other){
if(this.yourInt == other.yourInt) return 0;
if(this.yourInt > other.yourInt) return 1;
return -1;
}
As you can see you must implement the compareTo method and return 0 if the other entry is equal to this, -1 is its bigger and 1 if it's smaller! This way the program will know how to sort these objects and you can just use the ArrayList's sort method!
Using Comparable and Comparator you can do this. This example will give you a clear idea of how to sort your list by a property of an object. In this example Student objects are sorted by their age.
example
Related
This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 1 year ago.
Context (not strictly necessary to understand the question):
I have to implement a collection of elements. The class is called DocumentCollection. It is essentially an array of lists (a rudimentary form of a hash array), better formulated: an array of references to the first element of each respective list.
I already implemented a basic constructor, which takes an int as size of the array, and puts null initialized lists in each bucket.
One method to implement is removeAll. My first idea was to generate a new collection of the same size as the original one, and assign this to this newly created collection.
Below the code of the method.
public boolean removeAll(){
if(isEmpty()){
return false;
}
int size = buckets.length;
this = new DocumentCollection(size);
return true;
}
where buckets is the array.
As this is part of an assignment, I don't want to include the code of the whole class. This is enough for my question.
Intellij gives me the following error message (w.r.t. the line with this): variable expected.
Unfortunately this message is not eloquent enough for me to understand it.
Aside Note: yes, I could iterate over the array and assign null lists to them. That's not the point I am trying to make here
Question:
Am I doing something fundamentally wrong? In other words, is trying to give a new reference to the current object (i.e. this) illegal? Or can it be done, and I am simply using some wrong syntax?
You can't assign a new value to this since it is just a keyword to represent the current object along the class code, it is not a variable.
Beside's that, think of the semantics: you are inside the object asking it to become another object, that would be very tricky!
The closest you can get to that is to wrap some object as a field of your class, then you can assign a new instance to this field. Like this:
class MyObjectWrapper{
private MyObject myObject = new MyObject();
...
public void removeAll() {
this.myObject = new MyObject();
}
}
Check this related question: Why is assignment to 'this' not allowed in java?
This question already has answers here:
compareTo() vs. equals()
(21 answers)
Closed 6 years ago.
In this example I have an Employee class that implements Comparable, and below is the code for compareTo()
#Override
public int compareTo(Employee e) {
if (getName().equals(e.getName())) return 0;
else if (getPay() < e.getPay()) return -1;
else return 1;
}
When I do employee1.equals(employee2); , given that employee1 and 2 have the same name, I am expecting the result to be true but it returns false.
But when I did employee1.compareTo(employee2); I get the expected result, which is 0.
Please help me understand the nature of Comparable. Thanks!
The point of Comparable is to answer the question "If I were to put these things (in this case, Employees) in order, how would I know whether one should be in front of or behind the other? This means that it is essential that the fields you are checking in compareTo are exactly the same as those you are checking in equals. This helps to make these two consistent.
It is also important that your compareTo method is consistent with itself - in other words, Math.signum(a.compareTo(b)) = -Math.signum(b.compareTo(a)). In your case, two employees with different names and the same pay would always return 1, which means that both of these employees are supposed to come after each other when sorted (which doesn't make sense).
compareTo and equals methods are completely unrelated from the perspective of the JVM. It is programmer's duty to make natural order consistent with equals.
If only compareTo method is provided for the class Employee, the default implementations, derived from Object is inherited. You should override equals method (together with hasCode) to get consistent results.
You need to provide implementation for equals method (that will compare names) in Employee otherwise Java uses references equality check, thus two objects with the same name are not equal.
This question already has answers here:
Java vector capacity finding the vector size
(2 answers)
Closed 8 years ago.
I have this code.
import java.util.Vector;
import java.util.Enumeration;
/*Part Of My Private Code*/
private Vector clietns = new Vector();
private DataOutputStream remoteOut;
/*Part Of My Private Code*/
clients.addElement(remoteOut);
/*Part Of My Private Code*/
Enumeration e = clients.elements();
System.out.println(e + "");
This returns the hex code of Enumeration e.
How could I obtain the exact number of elements (in integer).
With the method size() from Vector. Enumeration doesn't give you that method, since it can be used to enumerate elements even if the full number isn't known.
Next time you're wondering a thing like this, please go see the Javadocs first.
As a last tip, Vector and Enumeration are considered outdated. You should use ArrayList and Iterator instead.
Use the Vector.size method. It will tell you the number of elements in the vector.
I think you cannot get the number of items from an Enumeration.
Note that the only two methods of this interface are:
hasMoreElements()
E nextElement()
So it is not intended to behave as a collection that usually knows the number of items inside them.
You should use vector size() method instead that returns an integer.
Questions like this are best to do a little research before posting.
Take a look at the API page for Java and you'll find what you're looking for. (Hint, the function is going to return an int)
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 9 years ago.
I'm trying to sort a ConcurrentSkipListMap by value in Java, here is my code :
ConcurrentSkipListMap<String,Float> cslMap = new ConcurrentSkipListMap(new Comparator() {
public int compare(Object o1,Object o2) {
return ((Comparable)((Map.Entry)(o1)).getValue()).compareTo(((Map.Entry)(o2)).getValue());
}
});
cslMap_Map.put("B",0.2f);
cslMap_Map.put("A",0.1f);
cslMap_Map.put("C",1f);
Got an error message when compiling it:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry
What's the correct way to do it ?
Thanks for the answers, but in it's Java doc, it says "The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time", so how to supply it with a Comparator that sort by its values ?
A SkipList must be sorted by key in order to work. It is really a lot more like a tree than a hashmap in the way it looks things up. (The name 'Map' in the java implementation is to indicate that it implements the Map interface, should not imply it is a cousin of HashMap or ConcurrentHashMap as an actual data structure.)
It "Skips" to different points in the list based on the result of comparing the lookup key to the current node-level, and narrows down where in the list the key you're looking for is. If it's not sorted, you'll just dead-end or jump around forever and never find anything.
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 7 years ago.
Is There a java util method, or a short way to sort an Array of some type by an attribute of that type. I currently have an array of Choice type objects where each have a getText() method that returns the visual representation of the choice. I can make a long method that creates an array of the choices texts, sort them, get their ordered index and then order the choices by that index, but I surely think there is some kind of a shortcut.
Any Suggestions?
Collections.sort(list, new Comparator<Choice>(){
public int compare (Choise c1, Choice c2) {
return c1.getText().compareTo(c2.getText());
}
});
add check for null if necessary
you can move comparator to external class and use reflection to read custom field from any object. but this will make code less understandable