Search Results

Search found 359 results on 15 pages for 'comparable'.

Page 1/15 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • how can I implement Comparable more than once?

    - by codeman73
    I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying to implement Comparable for 2 types. Here's my situation: I've got the following classes/interfaces: interface Foo extends Comparable<Foo> interface Bar extends Comparable<Bar> abstract class BarDescription implements Bar class FooBar extends BarDescription implements Foo With this, I get the error 'interface Comparable cannot be implemented more than once with different arguments...' Why can't I have a compareTo(Foo foo) implemented in FooBar, and also a compareTo(Bar) implemented in BarDescription? Isn't this simply method overloading?

    Read the article

  • Why doesn't java.lang.Number implement Comparable?

    - by Julien Chastang
    Does anyone know why java.lang.Number does not implement Comparable? This means that you cannot sort Numbers with Collections.sort which seems to me a little strange. Post discussion update: Thanks for all the helpful responses. I ended up doing some more research about this topic. The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns. For a bit of review, java.lang.Number is the abstract super-type of AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long and Short. On that list, AtomicInteger and AtomicLong to do not implement Comparable. Digging around, I discovered that it is not a good practice to implement Comparable on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong and AtomicInteger are mutable. The API designers had the forethought to not have Number implement Comparable because it would have constrained implementation of future subtypes. Indeed, AtomicLong and AtomicInteger were added in Java 1.5 long after java.lang.Number was initially implemented. Apart from mutability, there are probably other considerations here too. A compareTo implementation in Number would have to promote all numeric values to BigDecimal because it is capable of accommodating all the Number sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.

    Read the article

  • Comparable and Comparator contract with regards to null

    - by polygenelubricants
    Comparable contract specifies that e.compareTo(null) must throw NullPointerException. From the API: Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false. On the other hand, Comparator API mentions nothing about what needs to happen when comparing null. Consider the following attempt of a generic method that takes a Comparable, and return a Comparator for it that puts null as the minimum element. static <T extends Comparable<? super T>> Comparator<T> nullComparableComparator() { return new Comparator<T>() { @Override public int compare(T el1, T el2) { return el1 == null ? -1 : el2 == null ? +1 : el1.compareTo(el2); } }; } This allows us to do the following: List<Integer> numbers = new ArrayList<Integer>( Arrays.asList(3, 2, 1, null, null, 0) ); Comparator<Integer> numbersComp = nullComparableComparator(); Collections.sort(numbers, numbersComp); System.out.println(numbers); // "[null, null, 0, 1, 2, 3]" List<String> names = new ArrayList<String>( Arrays.asList("Bob", null, "Alice", "Carol") ); Comparator<String> namesComp = nullComparableComparator(); Collections.sort(names, namesComp); System.out.println(names); // "[null, Alice, Bob, Carol]" So the questions are: Is this an acceptable use of a Comparator, or is it violating an unwritten rule regarding comparing null and throwing NullPointerException? Is it ever a good idea to even have to sort a List containing null elements, or is that a sure sign of a design error?

    Read the article

  • Using Comparable to compare objects and sorting them in a TreeMap

    - by arjacsoh
    II cannot understand how should the natural ordering of class be "consistent with equals" when implementing the Comparable interface. I deteted a flaw in my program and therefore I deteced that in the documentantion of the interface Comparable. My problem is that although two Objects are considered as distinct on the base of equals method, the TreeMap structure treats them as equal and consequently does not accept the second insert. The sample code is: public class Car implements Comparable<Car> { int weight; String name; public Car(int w, String n) { weight=w; name=n; } public boolean equals(Object o){ if(o instanceof Car){ Car d = (Car)o; return ((d.name.equals(name)) && (d.weight==weight)); } return false; } public int hashCode(){ return weight/2 + 17; } public String toString(){ return "I am " +name+ " !!!"; } public int compareTo(Car d){ if(this.weight>d.weight) return 1; else if(this.weight<d.weight) return -1; else return 0; } /*public int compareTo(Car d){ return this.name.compareTo(d.name); }*/ } public static void main(String[] args) { Car d1 = new Car(100, "a"); Car d2 = new Car(110, "b"); Car d3 = new Car(110, "c"); Car d4 = new Car(100, "a"); Map<Car, Integer> m = new HashMap<Car, Integer>(); m.put(d1, 1); m.put(d2, 2); m.put(d3, 3); m.put(d4, 16); for(Map.Entry<Car, Integer> me : m.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); TreeMap<Car, Integer> tm = new TreeMap<Car, Integer>(m); System.out.println("After Sorting: "); for(Map.Entry<Car, Integer> me : tm.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); } The output is : I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am c !!! 2 That is, that the object c has replaced (somewhat) object b. If I comment the original equals method and uncomment the second equals method, which compares the objects according name, the output is the expected: I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am b !!! 2 I am c !!! 3 Why does it come around in this way and what should I alter in order to insert and sort different objects with some attributes of equal value in a TreeMap?

    Read the article

  • MyClass cannot be cast to java.lang.Comparable: java.lang.ClassCastException

    - by user2234225
    I am doing a java project and I got this problem and don't know how to fix it. The classes in my project (simplified): public class Item { private String itemID; private Integer price; public Integer getPrice() { return this.price; } } public class Store { private String storeID; private String address; } public class Stock { private Item item; private Store store; private Integer itemCount; public Integer getInventoryValue() { return this.item.getPrice() * this.itemCount; } } Then I try to sort an ArrayList of Stock so I create another class called CompareByValue public class CompareByValue implements Comparator<Stock> { @Override public int compare(Stock stock1, Stock stock2) { return (stock1.getInventoryValue() - stock2.getInventoryValue()); } } When I try to run the program, it gives the error: Exception in thread "main" java.lang.ClassCastException: Stock cannot be cast to java.lang.Comparable Anyone know what's wrong?

    Read the article

  • Looking for a Python UI library comparable with Windows Forms [on hold]

    - by Mitten
    I am looking for a Python UI library which I could use to develop a desktop GUI comparable to what can be done with .NET Windows Forms. I have no previous experience programming UI in Python, so I would rather choose (if there is a choice) something simple. The application I am building would be a document oriented - rich texts, lists and grids, I don't expect to use much graphics - mostly formatted texts. Any pointers, and if there is more than one major GUI library available for Python - how could I quickly test them to see which one is a better fit for my needs?

    Read the article

  • Does the specific signed integer matter when implementing compareTo in a Comparable <Type> class?

    - by javanix
    When implementing compareTo(), does the degree of "difference" need to be taken into account? For instance, if I have 3 objects, C1, C2, and C3, such that C1 < C2 < C3. Should C1.compareTo(C2) return an integer that is less than C2.compareTo(C3)? The documentation for the Comparable interface doesn't seem to specify one way or another, so I'm guessing the degree doesn't matter, but it would be nice to know if there is some advantage returning a specific number (for example, improving TreeSet sort speed or something). http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo(T)

    Read the article

  • Applying to a company while personally working on a comparable project

    - by Developer Art
    That's going to be an unusual question but here it goes. I'm entertaining the thought to send my docs to a place which develops a large web project of a social type. Social meaning people, communities, interaction and all that usual stuff. The issue is that I myself am working on something that falls into the category of social in my private time. Now the question. Is it wise to apply there under these circumstances? I think there may be issues of intellectual ownership if I develop something similar that exists or will exist in that company's work. On the other hand, the web of full of social places (even this site is one of them), many of them utilize the same ideas and move in the same direction and it seems to work for everyone. It's hard to come up with something which hasn't been tried yet by somebody else so it's all basically reuse of the commonly available ideas and experience. What I'm working on is not a functional equivalent, it's rather largely off. There may be some intersections, but on a large scale this is not an equivalent. And whatever features might coincide, they already exist everywhere on the web anyway. Also technology stacks are entirely different so the issue with directly copying out parts of the code is probably not applicable. I plan to say it up front that I'm engaged in a personal project of mine and let them see if it represents a problem for them. What do you think? Am I making things up or is there really an issue?

    Read the article

  • Java HashSet is allowing dupes; problem with comparable?

    - by IVR Avenger
    Hi, all. I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet. When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I set my breakpoints. Additionally, when I'm done with the add()s, I see several duplicates within the Set. What am I screwing up, here; why is it not Comparing, and therefore, allowing the dupes? Thanks, IVR Avenger

    Read the article

  • Unchecked call to compareTo

    - by Dave Jarvis
    Background Create a Map that can be sorted by value. Problem The code executes as expected, but does not compile cleanly: http://pastebin.com/bWhbHQmT The syntax for passing Comparable as a generic parameter along to the Map.Entry<K, V> (where V must be Comparable?) -- so that the (Comparable) typecast shown in the warning can be dropped -- eludes me. Warning Compiler's cantankerous complaint: SortableValueMap.java:24: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() ); Question How can the code be changed to compile without any warnings (without suppressing them while compiling with -Xlint:unchecked)? Related TreeMap sort by value How to sort a Map on the values in Java? http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/ Thank you!

    Read the article

  • How come Java doesn't accept my LinkedList in a Generic, but accepts its own?

    - by master chief
    For a class assignment, we can't use any of the languages bultin types, so I'm stuck with my own list. Anyway, here's the situation: public class CrazyStructure <T extends Comparable<? super T>> { MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound } However: public class CrazyStructure <T extends Comparable<? super T>> { LinkedList<MyTree<T>> trees; } Works. MyTree impleements the Comparable interface, but MyLinkedList doesn't. However, Java's LinkedList doesn't implement it either, according to this. So what's the problem and how do I fix it? MyLinkedList: public class MyLinkedList<T extends Comparable<? super T>> { private class Node<T> { private Node<T> next; private T data; protected Node(); protected Node(final T value); } Node<T> firstNode; public MyLinkedList(); public MyLinkedList(T value); //calls node1.value.compareTo(node2.value) private int compareElements(final Node<T> node1, final Node<T> node2); public void insert(T value); public void remove(T value); } MyTree: public class LeftistTree<T extends Comparable<? super T>> implements Comparable { private class Node<T> { private Node<T> left, right; private T data; private int dist; protected Node(); protected Node(final T value); } private Node<T> root; public LeftistTree(); public LeftistTree(final T value); public Node getRoot(); //calls node1.value.compareTo(node2.value) private int compareElements(final Node node1, final Node node2); private Node<T> merge(Node node1, Node node2); public void insert(final T value); public T extractMin(); public int compareTo(final Object param); }

    Read the article

  • How to make schema dumps comparable between Windows and Linux

    - by Jonathan
    I have two systems running, one on linux and the other on windows. From the linux box, I ran pg_dump against both systems and dumped the schema. pg_dump command: pg_dump -h HOST -U USER -s -f /tmp/out.sql DB_NAME After I removed all of the "--" comments, I diffed the files together. Diff output snippet, linux compared to windows: - ADD CONSTRAINT sys_c004775 FOREIGN KEY (ruleid) REFERENCES rule(ruleid); + ADD CONSTRAINT sys_c004775 FOREIGN KEY (ruleid) REFERENCES "rule"(ruleid); The linux dump does not quote any entities and windows does. Is this a function of some encoding or just of a difference between windows and linux? Is there an option in pg_dump to make the output more consistent?

    Read the article

  • Java: How to workaround the lack of Equatable interface?

    - by java.is.for.desktop
    Hello, everyone! As far as I know, things such as SortedMap or SortedSet, use compareTo (rather than equals) on Comparable<?> types for checking equality (contains, containsKey). But what if certain types are equatable by concept, but not comparable? I have to declare a Comparator<?> and override the method int compareTo(T o1, To2). OK, I can return 0 for instances which are considered equal. But, for unqeual instances, what do I return when an order is not evident? Is the approach of using SortedMap or SortedSet on equatable but (by concept) not comparable types good anyway? Thank you! EDIT: I don't want to store things sorted, but would I use "usual" Map and Set, I couldn't "override" the equality-behavior. EDIT 2: Why I can't just override equals(...): I need to alter the equality-behavior of a foreign class. Can't edit it. EDIT 3: Just think of .NET: They have IEquatable interface which cat alter the equality-behavior without touching the comparable behavior.

    Read the article

  • Java generic Comparable where subclasses can't compare to eachother

    - by dege
    public abstract class MyAbs implements Comparable<MyAbs> This would work but then I would be able to compare class A and B with each other if they both extend MyAbs. What I want to accomplish however is the exact opposite. So does anyone know a way to get the generic type to be the own class? Seemed like such a simple thing at first... Edit: To explain it a little further with an example. Say you have an abstract class animals, then you extend it with Dogs and ants. I wouldn't want to compare ants with Dogs but I however would want to compare one dog with another. The dog might have a variable saying what color it is and that is what I want to use in the compareTo method. However when it comes to ants I would rather want to compare ant's size than their color. Hope that clears it up. Could possibly be a design flaw however.

    Read the article

  • Is there anything RAD comparable to VCL?

    - by mawg
    After years in embedded programming, I have to develop a Windows app. I dug out my old C++ Builder and Delphi. These are great and the latest version costs over $1k, so I won't be going there. What I prarticularly like is the VCL (visual component library) which let's me code my own components and share them with others, plus the thousands of existing 3rd party components. I noticed that there is now also a RAD PHP from Borland too. I realzie that MSVC, QT, NetBeans, etc are good enough IDEs for RAD, BUT does anything offer the ease of the Borland products for developing additional components - and does anything else have thousands to choose from? PC based? Cross-platform is good. Browser based? Free is always good ;-) I don't particularly care about the programming language.

    Read the article

  • Are jQuery and GWT comparable frameworks?

    - by lomaxx
    At work there's a bit of discussion around what client side framework we should use for our front end web applications. Currently it's a showdown between GWT and jQuery and I'm kind of on the fence but leaning towards jQuery. From what I can tell, GWT and jQuery are trying to solve different problems but are compared to each other because they both end up existing in the web applications space. I suspect that if this is the case, then comparing the two may be fruitless so what I'm trying to get my head around is if comparing jQuery to GWT is even an apples to apples comparison in the same way that jQuery and ExtJS can be compared, or would it be more beneficial for our team to ask certain questions of our application and use the answers to determine which framework is a better fit for us?

    Read the article

  • Designing small comparable objects

    - by Thomas Ahle
    Intro Consider you have a list of key/value pairs: (0,a) (1,b) (2,c) You have a function, that inserts a new value between two current pairs, and you need to give it a key that keeps the order: (0,a) (0.5,z) (1,b) (2,c) Here the new key was chosen as the average between the average of keys of the bounding pairs. The problem is, that you list may have milions of inserts. If these inserts are all put close to each other, you may end up with keys such to 2^(-1000000), which are not easily storagable in any standard nor special number class. The problem How can you design a system for generating keys that: Gives the correct result (larger/smaller than) when compared to all the rest of the keys. Takes up only O(logn) memory (where n is the number of items in the list). My tries First I tried different number classes. Like fractions and even polynomium, but I could always find examples where the key size would grow linear with the number of inserts. Then I thought about saving pointers to a number of other keys, and saving the lower/greater than relationship, but that would always require at least O(sqrt) memory and time for comparison. Extra info: Ideally the algorithm shouldn't break when pairs are deleted from the list.

    Read the article

  • Direct comparator in Java out of the box

    - by KARASZI István
    I have a method which needs a Comparator for one of its parameters. I would like to pass a Comparator which does a normal comparison and a reverse comparator which does in reverse. java.util.Collections provides a reverseOrder() this is good for the reverse comparison, but I could not find any normal Comparator. The only solution what came into my mind is Collections.reverseOrder(Collections.reverseOrder()). but I don't like it because the double method calling inside. Of course I could write a NormalComparator like this: public class NormalComparator<T extends Comparable> implements Comparator<T> { public int compare(T o1, T o2) { return o1.compareTo(o2); } } But I'm really surprised that Java doesn't have a solution for this out of the box.

    Read the article

  • Consistent Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • Consistent HashCode() and Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • C# .NET: Ascending comparison of a SortedDictionary?

    - by Rosarch
    I'm want a IDictionary<float, foo> that returns the larges values of the key first. private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new AscendingComparer<float>()); class AscendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -y.CompareTo(x); } } However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here. Just to see what would happen, I removed the - sign from the comparator: public int Compare(T x, T y) { return y.CompareTo(x); } But I got the same result. This reinforces my intuition that I'm making a stupid error.

    Read the article

  • C# .NET: Descending comparison of a SortedDictionary?

    - by Rosarch
    I'm want a IDictionary<float, foo> that returns the larges values of the key first. private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new DescendingComparer<float>()); class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -y.CompareTo(x); } } However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here. Just to see what would happen, I removed the - sign from the comparator: public int Compare(T x, T y) { return y.CompareTo(x); } But I got the same result. This reinforces my intuition that I'm making a stupid error. This is the code that accesses the dictionary: foreach (KeyValuePair<float, foo> kv in sortedLayers) { // ... } UPDATE: This works, but is too slow to call as frequently as I need to call this method: IOrderedEnumerable<KeyValuePair<float, foo>> sortedLayers = layers.OrderByDescending(kv => kv.Key); foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { // ... } UPDATE: I put a break point in the comparator that never gets hit as I add and remove kv pairs from the dictionary. What could this mean?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >