Using a Comparator to Compare Comparables

I have a class which can wrap Comparable objects. The idea is similar to C++'s "Pair" class. Until recently, it worked fine. Then, I "fixed" an unchecked warning I found and I can't seem to get the thing to work now.
A good sample of this code looks like this:
public static class A<T,U>
    public T t;
    public U u;
    public A(T t, U u)
        this.t = t;
        this.u = u;
public static class AComp<T extends Comparable<T>,U> implements Comparator<A<T,U>>
    public int compare(A<T, U> x, A<T, U> y)
        return x.t.compareTo(y.t);
List<A<Comparable,String>> list = new ArrayList<A<Comparable,String>>();
for (int i=0;i<5;i++)
    list.add(new A<Comparable,String>(i, String.valueOf(i)));
Collections.sort(list, new AComp<Comparable,String>());The last line fails compilation with the error message "type parameter java.lang.Comparable is not within its bound." The problem seems to be caused by the change I made to the comparator. It used to read
public static class AComp<T extends Comparable,U> implements Comparator<A<T,U>>(Note the lack of a type: "T extends Comparable" instead of "T extends Comparable<T>".) This compiles but produces an unchecked warning on the line in the compare method.
How do I fix this? I want to rid myself of the unchecked warning and I want my code to compile. This doesn't seem like an inherently unsafe operation...
Silly reflexive Comparable definition. Any ideas?
Thanks!

That's just the issue I'm having. My sample code functions as long as the parameterized type being compared isn't Comparable. For example, changing the type to A<Integer,String> works fine.
I think I may have discovered why this is the case. By declaring A<Comparable,String>, I am implying that the first parameterized type (call it T) is Comparable<T>. As a result, what I need is an A<Comparable<Comparable>, String>; that is, anything which is comparable must be able to be compared to the object. Since Integer is only Comparable<Integer>, it cannot be compared to all Comparable objects and therefore doesn't meet the requirements.
I'm not used to looking the other way on the inheritance tree. :)
The original trouble I had with this came from when I was passing a hash code generator into a piece of source and I needed to compare the hashes. The only guarantee I have regarding the hashes is that they are Comparable and I was putting them in a similar Pair structure. I then wanted to build a comparator to compare them but, since they're Comparable<?>, I can't know to what they can be compared... so I'll have to change the contract on the code. ;)
Thanks. Cheers. :)

Similar Messages

  • Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems n

    Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems never arose during two years of using LTR-4 and nothing else has changed on my computer.  I have a pretty simple system with only a few plug-ins, which are usually not in operation.  I have 12GB of RAM in my Windows 7 PC.  I could illustrate these problems with screen shots if you would tell me how to submit screen shots.  Otherwise I will try to describe the problems in words.
    The problem is clearly cumulative, growing worse as usage time passes.  Compare View feature gradually slows down and eventually seems to choke as my work session proceeds. If I Exit LTR and re-enter and start all over, things will work normally for maybe 30 minutes, but then the Compare View feature begins to become very slow to respond.   In a recent example with my screen full of thumbnails in Library mode I highlighted two images to compare. LTR started to open the Compare View screen by first having the top row of thumbnails disappear to be replaced by the "SELECT" and "CANDIDATE" words in their spaces  (but no images), but Compare View never succeeded in gaining control of the screen. After some seconds the top row of thumbnails reasserted its position and the Compare View windows disappeared. But LTR kept trying to bring them back. Again the top row of thumbnails would go away, Select and candidate would reappear, try again, and give up. This went on for at least 2-3 minutes before I tried to choose File and Exit, but even that did not initially want to respond. It doesn't like to accept other commands when it's trying to open Compare View. Finally it allowed me to exit.
    To experiment I created a new catalog of 1100 images.  After 30-40 minutes, the Compare View function began to operate very slowly. With left and right side panels visible and two thumbnails highlighted, hitting Compare View can take half a minute before the two mid-size  images open in their respective SELECT and CANDIDATE windows. When the side panels are open and two images are in the Select/Candidate spaces, hitting the Tab button to close the side panels produces a very delayed response--25-30 seconds to close them, a few more seconds to enlarge the two images to full size. To reverse the process (i.e., to recall the two side panels), hitting Tab would make the two sides of the screen go black for up to a minute, with no words visible. Eventually the info fields in the panels would open up.
    I also created a new user account and imported a folder of 160 images. After half an hour Compare View began mis-placing data.  (I have a screen shot to show this.)  CANDIDATE appears on the left side of SELECT, whereas it should be on the right. The accompanying camera exposure data appears almost entirely to the left of the mid-screen dividing line. Although the Candidate and Select headings were transposed, the image exposure data was not, but the data for the image on the right was almost entirely to the left of the line dividing the screen in two.
    Gurus in The Lightroom Forum have examined Task Manager data showing Processes running and Performance indicators and they see nothing wrong.  I could also send screen shots of this data.
    At this point, the only way I can process my images is to work 30-40 minutes and then shut down everything, exit, and re-start LTR.  This is not normal.  I hope you can find the cause, and then the solution.  If you would like to see my screen shots, tell me how to submit them.
    Ollie
    [email protected]

    Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems never arose during two years of using LTR-4 and nothing else has changed on my computer.  I have a pretty simple system with only a few plug-ins, which are usually not in operation.  I have 12GB of RAM in my Windows 7 PC.  I could illustrate these problems with screen shots if you would tell me how to submit screen shots.  Otherwise I will try to describe the problems in words.
    The problem is clearly cumulative, growing worse as usage time passes.  Compare View feature gradually slows down and eventually seems to choke as my work session proceeds. If I Exit LTR and re-enter and start all over, things will work normally for maybe 30 minutes, but then the Compare View feature begins to become very slow to respond.   In a recent example with my screen full of thumbnails in Library mode I highlighted two images to compare. LTR started to open the Compare View screen by first having the top row of thumbnails disappear to be replaced by the "SELECT" and "CANDIDATE" words in their spaces  (but no images), but Compare View never succeeded in gaining control of the screen. After some seconds the top row of thumbnails reasserted its position and the Compare View windows disappeared. But LTR kept trying to bring them back. Again the top row of thumbnails would go away, Select and candidate would reappear, try again, and give up. This went on for at least 2-3 minutes before I tried to choose File and Exit, but even that did not initially want to respond. It doesn't like to accept other commands when it's trying to open Compare View. Finally it allowed me to exit.
    To experiment I created a new catalog of 1100 images.  After 30-40 minutes, the Compare View function began to operate very slowly. With left and right side panels visible and two thumbnails highlighted, hitting Compare View can take half a minute before the two mid-size  images open in their respective SELECT and CANDIDATE windows. When the side panels are open and two images are in the Select/Candidate spaces, hitting the Tab button to close the side panels produces a very delayed response--25-30 seconds to close them, a few more seconds to enlarge the two images to full size. To reverse the process (i.e., to recall the two side panels), hitting Tab would make the two sides of the screen go black for up to a minute, with no words visible. Eventually the info fields in the panels would open up.
    I also created a new user account and imported a folder of 160 images. After half an hour Compare View began mis-placing data.  (I have a screen shot to show this.)  CANDIDATE appears on the left side of SELECT, whereas it should be on the right. The accompanying camera exposure data appears almost entirely to the left of the mid-screen dividing line. Although the Candidate and Select headings were transposed, the image exposure data was not, but the data for the image on the right was almost entirely to the left of the line dividing the screen in two.
    Gurus in The Lightroom Forum have examined Task Manager data showing Processes running and Performance indicators and they see nothing wrong.  I could also send screen shots of this data.
    At this point, the only way I can process my images is to work 30-40 minutes and then shut down everything, exit, and re-start LTR.  This is not normal.  I hope you can find the cause, and then the solution.  If you would like to see my screen shots, tell me how to submit them.
    Ollie
    [email protected]

  • Can oracle text be used to compare documents?

    lets say that i 've some documents stored in binary(LOB). can oracle text be used to compare documents and show their similarity on the basis of their content. how would i be able to compare documents using Oracle text. does it require mining algorithm like neural network. please help.
    thanks for reading.

    Thank you for your interest in my question. Let me see whether  I can further clarify it. In an ordinary PDF document, assume that I have a picture of a user interface for microsoft Word. The common method for identifying items in the picture, such as a toolbar, would be to either:
    --use a callout labeled "toolbar" that points to the toolbar
    or 
    --use a callout labelled "A" and have a caption underneath the picture that says: A) toolbar.
    What I would like to do is have text underneath the picture such as:
    "The major features of the interface shown above are:
    toolbar
    main menu
    status bar
    formatting menu"
    such that, when the user clicks one of the bullet items, the object becomes highlighted in the picture. The bullet list also needs to be translatable into Japanese. So, as far as I know, it can't be part of the swf file. Or can it?

  • What are advantage of using ARIS compare to MS Visio?

    Hi,
    what are advantage of using ARIS compare to MS Visio?
    How we can say ARIS is best for SAP implementaion?
    Pls let me know the details.

    Hi Anandh,
    There are a lot of differences between ARIS and Visio, however the main difference between these 2 products is that ARIS is a database in a client server architecture while Visio is a visual modeler with unstructured data.
    You could imagine then what you can do with information in a database like Aris: query the objects (processes, roles, activities, etc) by their attributes (owner, relationships), you can have several different views on the information, this is, the IT guy would like to see which IT systems are supporting the opperation of certain process while the COO would like to know in which countries are these proceses running.
    You may want to have a closer look to what we call the Enterprise Architecture (SAP EAF). This is not only the definition of landscape but the blueprinting of the whole organization, meaning Business, Data, Applications and Infraestructure Architecture.
    Have a look to this link also:
    SAP EAF: Aligning IT to Business
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/c0da74aa-6f2e-2a10-6387-edbf382f3f87
    Best Reagards.
    Oliver

  • Example of a Treemap using a Comparator?

    I'm in need of a small example of using a Treemap (with generics, of course) using a Comparator. For example:
    TreeMap tm = new TreeMap<Foo,Short>(new ComparatorTest<Foo>());
    for some class Foo, which I'm mapping to Short.
    I've tried taking an old non-generic example and adding in the new pieces, but the java compiler isn't nice about indicating what I've done wrong.
    Any examples out there?
    Thanks

    OK, I've fixed my declaration to be:
    TreeMap<MppInfo,Short> tm = new TreeMap<MppInfo,Short>(new ComparatorTest<MppInfo>());
    My code is:
    class MppInfo {
    public String badgeId;
    public String mppRollupLevel;
    public String month;
    public String year;
    class ComparatorTest<MppInfo> implements Comparator<MppInfo> {
    public int compare(MppInfo a, MppInfo b) {
    int val = a.badgeId.compareTo( b.badgeId );
    if ( val != 0 ) {
    return val;
    val = a.mppRollupLevel.compareTo( b.mppRollupLevel );
    if ( val != 0 ) {
    return val;
    val = a.month.compareTo( b.month );
    if ( val != 0 ) {
    return val;
    val = a.year.compareTo( b.year );
    if ( val != 0 ) {
    return val;
    return 0;
    public boolean equals(Object o) {
    MppInfo s = (MppInfo)o;
    return compare(this, s) == 0;
    ...the java compiler does not like my code at all:
    ReadMPP.java:436: cannot find symbol
    symbol : variable badgeId
    location: class java.lang.Object
    int val = a.badgeId.compareTo( b.badgeId );
    ^
    ReadMPP.java:436: cannot find symbol
    symbol : variable badgeId
    location: class java.lang.Object
    int val = a.badgeId.compareTo( b.badgeId );
    ^
    ...deleting similar errors.
    ReadMPP.java:457: compare(MppInfo,MppInfo) in com.ctc.PmPlanning.ReadMPP.ComparatorTest<MppInfo> cannot be applied to (com.ctc.PmPlanning.ReadMPP.ComparatorTest<MppInfo>,MppInfo)
    return compare(this, s) == 0;
    ^
    Note: ReadMPP.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    9 errors

  • How come the JRE uses == to compare Strings?

    I was looking through the source of javax.swing.plaf.basic.BasicComboBoxUI and came across this:        public void propertyChange(PropertyChangeEvent e) {
                String propertyName = e.getPropertyName();
             JComboBox comboBox = (JComboBox)e.getSource();
                if ( propertyName == "model" ) {
                else if ( propertyName == "editor" && comboBox.isEditable() ) {
                else if ( propertyName == "editable" ) {
                else if ( propertyName == "enabled" ) {
                else if ( propertyName == "focusable" ) {
                else if ( propertyName == "maximumRowCount" ) {
                else if ( propertyName == "font" ) {
                else if ( propertyName == JComponent.TOOL_TIP_TEXT_KEY ) {
                else if ( propertyName == BasicComboBoxUI.IS_TABLE_CELL_EDITOR ) {
             else if (propertyName == "prototypeDisplayValue") {
             else if (propertyName == "renderer") {
            }So
    1) Is there a valid reason for the developer to have used == instead of .equals(...) to compare Strings?
    2) How does the code work consistently with this anomaly?
    Similar use of == and not .equals(...) is seen in many other swing classes.
    Doesn't affect me, but I would be interested to know if anyone can throw some light on this.
    Thanks, Darryl

    Darryl.Burke wrote:
    DeltaGeek, thank you for your response.
    Paul, I think I understand what you are saying, but the String reference propertyNamein this case comes from e.getPropertyName() from the PropertyChangeEvent class, not from within the BasicComboBoxUI class.
    I gather that all loaded classes share the same String pool, and that's how this works correctly. But in that case any comparison of a String variable to a literal String using == should also work.
    Then why the brouhaha about never using == to compare Strings?The key thing here is that the String returned by getPropertyName() must have come from a String literal. For example, in javax.swing.JComboBox:
    firePropertyChange( "maximumRowCount", oldCount, maximumRowCount );This string literal will be the same instance as the string literal in the code you posted.
    If they had instead done something like
    String s = "RowCount";
    boolean isMaximum = true;
    firePropertyChange((isMaximum ? "maximum" : "minimum") + s, oldCount, maximumRowCount );In this case, the String literal "maximumRowCount" is not used, but rather created from a concatenation at runtime, so it's likely that the comparison would fail.
    Note that the following would be the same String literal because this concatenation would be done at compile-time, not runtime:
    "maximum" + "RowCount"As for why, I agree with DeltaGeek: performance.

  • Using a Comparable Class with Treeset, creating counter in comparable clas

    http://rafb.net/paste/results/jibQzk63.html - comparable http://rafb.net/paste/results/Noahue63.html - loading
    http://rafb.net/paste/results/re1Swn60.html - contents of .txt file * sorry the paste is weird lol.
    Trying to List word count in alphabetical order - Already did that
    Having a counter so it counts the number of time that specfic word appeared in the txt file - This is my problem I don't know where to add the counter in my comparable class so it stores a number and adds everytime that same word appears. ex. "and 7" the word "and" appeared 7 times in the .txt file
    so if some1 could help me, would be apperciated. I've like tried everything and getting the opposite results.

    That's just the issue I'm having. My sample code functions as long as the parameterized type being compared isn't Comparable. For example, changing the type to A<Integer,String> works fine.
    I think I may have discovered why this is the case. By declaring A<Comparable,String>, I am implying that the first parameterized type (call it T) is Comparable<T>. As a result, what I need is an A<Comparable<Comparable>, String>; that is, anything which is comparable must be able to be compared to the object. Since Integer is only Comparable<Integer>, it cannot be compared to all Comparable objects and therefore doesn't meet the requirements.
    I'm not used to looking the other way on the inheritance tree. :)
    The original trouble I had with this came from when I was passing a hash code generator into a piece of source and I needed to compare the hashes. The only guarantee I have regarding the hashes is that they are Comparable and I was putting them in a similar Pair structure. I then wanted to build a comparator to compare them but, since they're Comparable<?>, I can't know to what they can be compared... so I'll have to change the contract on the code. ;)
    Thanks. Cheers. :)

  • Using the Comparator Interface.Please Help.

    Hello there,
    I am trying out this example regarding the Comparator Interface.
    It works fine, but I havent really understood this at all.
    It deals with reverse sorting.
    import java.util.*;
    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;
    return bStr.compareTo(aStr)
    class MyComparator {
    public static void main(String[] args) {
    // Create a Tree Set
    TreeSet ts = new TreeSet(new MyComp());
    ts.add("C");
    ts.add("A");
    ts.add("P");
    ts.add("Z");
    ts.add("B");
    System.out.println(ts)
    Output : [Z, P, C, B, A]
    I have not understood the following at all:
    1) We are implementing the Comparator Interface in class MyComp.
    Now where is this being called in the MyComparator class?
    2) How is the reverse sorting taking place.?
    How is this comparing the different instances of the MyComparator class
    when I havent even instantiated the MyComparator class ?
    3) How is the interface method compare To(Object a,Object b) being invoked?
    Please can some please answer my questions.
    Regards

    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;Your reverse ordering is happening here.
    If you were to write
    return aStr.compareTo(bStr)
    the ordering would be in normal order.
    >
    return bStr.compareTo(aStr)The comparator that the treeSet uses is declared and instantiated here
    TreeSet ts = new TreeSet(new MyComp());
    1) We are implementing the Comparator Interface in
    class MyComp.
    Now where is this being called in the MyComparator
    or class? The comparator is being used by the TreeSet to order your entries
    >
    >
    2) How is the reverse sorting taking place.?Explained above. For further explaination look up comparator and String.compareTo()
    How is this comparing the different instances of
    of the MyComparator class
    when I havent even instantiated the MyComparator
    or class ?Also explained above
    3) How is the interface method compare To(Object
    a,Object b) being invoked?Internally by the TreeSet
    I hope this helped a little

  • FMB size changes when compiled using ifcmp60 compared to using ifbld60

    We observed that when we batch compiled our forms size of the FMB reduced quite a bit after batch compile and save compared
    to what it was to originally when compiled and saved through forms builder (ifbld60.EXE). If after this form is opened in
    forms builder and then compiled and saved it reverts to original size. We also checked using one of the third party form
    diff utility and found both FMB’s from batch compile and one from form builder even though of different size do not have any
    difference.
    Now question sis what is the reason FMB size is reduced and does it not pose any kind of issue for loosing something out of
    the FMB. Please explain what is this behavior with impact if any etc?
    We batch compile using the following code.
    For %%I in (sizechange.FMB) do start /w ifcmp60 module=%%I userid=usrname/passwd@SID batch=yes compile_all=yes Upgrade=No
    build=Yes
    We made a sample form named sizechange.fmb with non-db block and having program unit selecting from dual multiple times.
    Environment details : Windwos 2000, Forms 6.0.8.22.1, db(8.0.6.0.0) on HP9000-UX 10.20
    Thanks in advance for your response.
    Vinay Gupta
    I am not sure where to upload sample file, if someone needs it I can email it.
    Thanks,

    Didn't see they where timestamps . Yes it seems that glx is one cause of the delay. I've tried some different xorg.conf, and it's always ligglx.so or  NV-GLX that slows it down. Any suggestions on how I can speed this up?
    ps. The computer is ok. Although the garddrive is a SATA 3.0Gb/s, 5400 RPM.  But I don't think this is the problem?

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • What type of chart should we use for comparing more than 200 items

    Hi Guys, 
    I have a Pie chart graph for comparing data items but this chart becomes cluttered or serves no purpose when categories increase up to 100 or 200 items.
    I have tried collected Pie but still facing same issue.
    When the numbers of Legends increases the chart will become cluttered and this will reduce it readability as shown in the image.  Please share your suggestions for suitable chart type or strategy to overcome this issue.
    Regards

    Hi,
    As you may know, the issue is caused by the excessive items in the category group of the pie chart. The most direct and effective way is to reduce the items in the category group. Generally, we are not always need the report to display all items in the chart.
    In this scenario, we can add a parameter in the report, then use the parameter to filter the corresponding values in the chart.
    Besides, in order to increase the chart readability, we can try to use Column Chart to display those values. And we can “Enable scale breaks” in the Vertical Axis. A scale break is a stripe drawn across the plotting area of a chart to denote a break in continuity
    between the high and low values on a value axis. Use a scale break to display two distinct ranges in the same chart area.
    Reference:
    Add a parameter to filter the data in SSRS
    Add Scale Breaks to a Chart (Report Builder
    and SSRS)
    Hope this helps.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Stuck using the Comparable Interface

    I am having problems implementing the Comparable Interface in my class. I have written the compareTo method but this is not working. Can anyone see what I am doing wrong in the coding of this method. Thanks !!. (see below code for the class :
    package tma02q1;
    import java.util.*;
    This is the outline of the basic Video class.
    Such a class describes the videos stocked by a branch of a video hire company
    As well as completing the given methods you will need to make further additions
    to this class.For further details you should study the BranchTest class.
    public class Video implements Comparable {
    // declare two instance variables
    // a String to hold the video title
    // an int to hold the video rental cost - cost is held in pence
    private String aTitle;
    private int aCost;
    public Video(String aTitle, int aCost) {
    this.aTitle = aTitle;
    this.aCost = aCost;
    private void setTitle(String aTitle) {
    this.aTitle = aTitle;
    public String getTitle() {
    return aTitle;
    private void setRentalCost(int aCost) {
    this.aCost = aCost;
    public int getRentalCost() {
    return aCost;
    public String toString() {
    return "Video Title = " + aTitle + " which has a rental cost of = " + aCost;
    public boolean equals(Object vid) {
    Video arg = (Video) vid;
    return (this.aTitle.equals(arg.aTitle)
    &&this.aCost==arg.aCost);
    public int compareTo(Object vido) {
    Video arg = (Video) vido;
    int comp = aCost.compareTo(arg.aCost);
    return comp;

    You've got another serious problem with your code. Both the equals and compareTo methods will throw a ClassCastException if the parameter is not a reference to a video object. Using the instanceof operator will however solve the problem. E.g.
    public boolean equals(Object o) {
      if (o instanceof Video) {
        Video  arg = (Video) o;
        return (this.aTitle.equals(arg.aTitle)
                &&this.aCost == arg.aCost);
      else
        return false;  
    }The same approach is applicable to the compareTo method.
    Regards

  • How to use the compare document option thru VB or command line

    Hi:
    I’m trying to automate the process of comparing two document thrue the option document/compare document in Adobe Acrobat Pro based on a list of files on an excel spreadsheet. Do you know how to do this thru VB code or a command line argument?
    Thanks

    Compare is not exposed via any API.

  • Sorting a combination of two longs using a comparator

    Hello to all,
    I need to implement a comparator that will take as input an object containing two longs, combine them and sort them in the form a.b, where a is the first long and b the second, first by a and then by b. (eg.1.2, 2.8, 1.5, 2.4, 3.4, 3.3, etc... becomes 1.2, 1.5, 2.4, 2.8, 3.3, 3.4, etc..)
    Is there a way to achieve this?
    Thank you in advance!

    like this?
    class LongComparator implements Comparator {
      String delimiter;
      public LongComparator(String delimiter) {
        this.delimiter = delimiter;
      public int compare(Object o1, Object o2) {
        String[] s1 = ((String) o1).split(delimiter);
        String[] s2 = ((String) o2).split(delimiter);
        Long l1s1 = Long.valueOf(s1[0]);
        Long l2s1 = Long.valueOf(s1[1]);
        Long l1s2 = Long.valueOf(s2[0]);
        Long l2s2 = Long.valueOf(s2[1]);
        if (l1s1.compareTo(l1s2) == 0) {
          return l2s1.compareTo(l2s2);
        } else {
          return l1s1.compareTo(l1s2);
    }

  • Using FileStream compared to C#.

    I am trying to covert the following C# code into JAVA codes
    Please help me out:
    FileInfo mFileInfo=new FileInfo(imageFile);
    BinaryReader binRead=new BinaryReader(mFileInfo.OpenRead());
    binRead.ReadBytes(2);
    originalSize=binRead.ReadInt32();
    binRead.ReadBytes(12);
    width=binRead.ReadInt32();
    height=binRead.ReadInt32();
    binRead.ReadBytes(28);
    I know that FileInfo and BinaryReader part can be just used as FileInputStream. However, I am not sure how ReadBytes works. Is there a similar fucntion for that? what is this code actually doing currently?
    Thank you.

    I am not that much familiour with but this might help
    In java you got 2 types of streams Character Streams and Byte Streams their name says how they read.
    FileInputStream is a byte stream meaning that it reads byte by byte.
    You got several read method in it that you can use
    int read(); //this reads one byte from stream return -1 if you have reach EOF
    int read(byte[] b); //This read at most b.length number of bytes from the stream in to b, Return the number of bytes read
    /*This is the more complicated version
    It read at most len number of bytes in to b starting from off indexed element of th array
    and return the number of bytes read
    int read(byte[] b, int off, int len);But if you want to read other types of data you can use DataInputStream
    And if you want to buffering capability you can use BufferedInputSeam
    For more information I suggest you to read the java io tutorial. Thn you can understand the difference between java io and C# io your self. But I dont think that there is much difference

Maybe you are looking for

  • AOL Contact in Jabber Client

    Has anyone been able to successfully set up an AOL Contact on their Jabber client? I'm using Jabber 8.6.4 for Mac and whenever I specify my wife's AIM account name and select the checkbox for "This is an AOL account", then click the "Add" button, I g

  • Using info from another website

    Hi there, I am very weak with my script knowledge ( i do have basic knowledge on Flash), so please excuse me if I'm posting my question in the wrong section. Basically, I'll like to work on a project to showcase my DVD collection (it's for practice).

  • Is it safe to increase LUN size of ASM disk online 11gR2 ?

    I have an Oracle 11gr2 ASM in a RAC, using an EMC SAN. I have one Disk Group (DATA), with one disk (DISK1), configured with external redundancy [Flash Recovery Area is non-ASM]. Red Hat Linux. My storage is a 450GB LUN, and I want to grow it by 150GB

  • One AR invoice failed to create accounting

    Hi, all We are using the Version 12.1.3 I have one AR invoice which fail to create accounting. I get the error number 95261 The account code combination 8F..ZZZZZZZZZ.000.000000.000000 is invalid. Please inform your system administrator or support re

  • Keep getting an error from securesite.co.uk about ...

    I have tried three times to pay for a skype number, and apparently it is just impossible to give any money to the company. I have tried emailing, I have tried to pay via the site three times, and I have had absolutely no luck. All I want to do is be