compareTo and Strings using a Scanner

2019-07-25 04:10发布

I am implementing a form of leftist min heap, which stores arbitrary words by length. So, I have written a wrapper class for Scanner, and changed the compareTo, like so

public class ScannerWrapper implements Comparable<String>

//a Scanner, sc and a String, current
public int compareTo(String str){
    if(current.length() > str.length()) return -1;
    if(current.length() > str.length()) return 1;
    else return 0;
}

where current = sc.next() and is not the \n character.

in this case, if I have ScannerWrapper.next() > foo , where foo is an arbitrary string of length > ScannerWrapper.next();
will it use the compareTo(String) that I have written, returning false, or will it do some other random thing?

2条回答
戒情不戒烟
2楼-- · 2019-07-25 04:25

It's difficult to understand your question - so you might consider rephrasing it. Here's a shot in the dark :

 public class ScannerWrapper implements Comparable<ScannerWrapper>

    //your wrapper has a handle to the scanned data.   Presumably it's
    //initialized on construction, which is omitted here
    private final String scannedData;        

    public String getScannedData() { 
        return this.scannedData;
    }

    public int compareTo(ScannerWrapper other) {
        //if this scannedData is longer than the other, return 1
        if(this.str.length() > other.getStr().length()) {
            return 1;
        } else if(this.scannedData.length() < other.getScannedData().length()) {
        //if the other scannedData is longer return -1   
            return -1;
        }
        //if they are equal return 0
        return 0;
    }

 }
查看更多
Anthone
3楼-- · 2019-07-25 04:31

After reading your question several times I think I understand what you're asking now. If you're trying to compare two instances of class ScannerWrapper with the comparison operators, then no, it's not going to work.

You can't overload operators in Java (you can in C++), therefore in order to compare instances of ScannerWrapper with each other you're going to have to call the compareTo() method.

Also, both of your if statement conditions are the same, so you might want to fix that up.

查看更多
登录 后发表回答