Reputation: 1366
I have a queue implementation as shown below.
static String a = "1 0 2014/03/03 01:34:39 0.0 0.0 0.0";
static String b = "2 1 2014/03/03 01:34:40 0.0 0.0 0.0";
static String c = "3 2 2014/03/03 01:34:41 0.0 0.0 0.0";
static String[] d;
String e;
public static void main(String[] args) {
Queue<String> s = new LinkedList<String>();
s.add(a);
s.add(b);
s.add(c);
}
As you see each entry in the list is a string with 7 elements. I would like to compare these entries from each string. For example the first entries from a, b, c using s.
Upvotes: 0
Views: 3167
Reputation: 8362
Here is an explanation of my comment, "Try creating a custom class for your strings and implementing the Comparable
interface. Then you could write your own compareTo
method."
Seeing as you have a very particular data type, you might create your own defined class. The following MyString
class encapsulates a String, implements the Comparable
interface, and provides an example of how you might use a compareTo
method for such a class.
public class MyString implements Comparable<MyString> {
private String data;
public MyString(String data) {
this.data = data;
}
public int compareTo(MyString other) {
String[] thisArray = new String[6];
String[] otherArray = new String[6];
thisArray = this.data.split(" ");
otherArray = other.data.split(" ");
// Compare each pair of values in an order of your choice
// Here I am only comparing the first two number values
if (!thisArray[0].equals(otherArray[0])) {
return thisArray[0].compareTo(otherArray[0]);
} else if (!thisArray[1].equals(otherArray[1])){
return thisArray[1].compareTo(otherArray[1]);
} else {
return 0;
}
}
}
The compareTo
method returns 1, 0, or -1 depending on whether value A is respectively greater than, equal to, or lesser than value B. Again, this is just an example and I am only comparing Strings. Here is an example of how you might compare two of your formatted Strings using this method:
MyString a = new MyString("1 0 2014/03/03 01:34:39 0.0 0.0 0.0");
MyString b = new MyString("1 1 2014/03/03 01:34:40 0.0 0.0 0.0");
// Do something with the compared value, in this case -1
System.out.println(a.compareTo(b));
Documentation on Comparable
and compareTo
can be found here.
Upvotes: 3