constructor - Java: If object of same parameters exists do not add new object -


here object constructor

static class edge {     int source; // source node     int destination; // destination node     int weight; // weight of edge     int predecessor; // previous node     public edge() {};     public edge(int s, int d, int w) { source = s; destination = d; weight = w; } } 

now, here statement create new edge object

edges.add(new edge(nodestart, tempdest, tempweight)); 

i need skip on statement if there has been object created same parameters (nodestart, tempdest)

basically, don't want add same edge twice.

edges.add(new edge(0, 1, tempweight)); edges.add(new edge(0, 1, tempweight)); 

if happens, want make sure adds once, , not new identical objects.

the proper way make edges set<edge>. , override hashcode , equals.

so, should declare edges so:

set<edge> egdes = new hashset<edge>(); 

and should implement hashcode , equals so:

public boolean equals(object o) {     if (o == null) return false;     if (o == this) return true;     if (!(o instanceof edge)) return false;     edge oedge = (edge) o;     return this.source == oedge.source &&             this.destination == oedge.destination &&             this.weight == oedge.weight; }  public int hashcode(){     return source * 3 + dest * 11 + weight * 13; } 

you should read on implementing equals , hashcode. examples not great. general idea conveyed.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -