| Author |
java class Comparator /
|
jite eghagha
Ranch Hand
Joined: Oct 06, 2006
Posts: 124
|
|
My understanding of how to use this class must be wrong. The code below (in my main): TreeSet allEdges = new TreeSet(new Edge()); gives this error: C:\doit.java:25: cannot find symbol symbol : constructor TreeSet(doit.Edge) The code: class Edge implements Comparator { // Inner class for representing edge+end-points public int from, to, cost; public Edge() { // Default constructor for TreeSet creation } public Edge(int f, int t, int c) { // Inner class constructor from = f; to = t; cost = c; } public int compare(Object o1, Object o2) { // Used for comparisions during add/remove operations int cost1 = ((Edge) o1).cost; int cost2 = ((Edge) o2).cost; int from1 = ((Edge) o1).from; int from2 = ((Edge) o2).from; int to1 = ((Edge) o1).to; int to2 = ((Edge) o2).to; if (cost1<cost2) return(-1); else if (cost1==cost2 && from1==from2 && to1==to2) return(0); else if (cost1==cost2) return(-1); else if (cost1>cost2) return(1); else return(0); } public boolean equals(Object obj) { // Used for comparisions during add/remove operations Edge e = (Edge) obj; return (cost==e.cost && from==e.from && to==e.to); } } thanks
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
You need to create the TreeSet first, and then add the Edge object to it.
|
 |
jite eghagha
Ranch Hand
Joined: Oct 06, 2006
Posts: 124
|
|
Thank you, But, i'll rephrase the question. TreeSet(Comparator c) Constructs a new, empty set, sorted according to the specified comparator. I thought if Edge implemented Comparator, i could use it in the constructor of TreeSet. as so: new TreeSet(new Edge()); Then i would be true i have things ordered as i specified. But that isn't the case, hence the error.
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
I'm sorry, I read the code wrong. If the Edge objects are things you'd like to compare, I think it would be better to either make each Edge object implement Comparable, or create a seperate Comparator.
|
 |
jite eghagha
Ranch Hand
Joined: Oct 06, 2006
Posts: 124
|
|
thank you, I get the idea.
|
 |
 |
|
|
subject: java class Comparator /
|
|
|