Search code examples
javatreesetsortedset

Storing Object and Updating it in Sorted Tree Set


I am using a Tree Set to store some Signals as objects in my Tree Set and also want to update an object If the same signal comes again. So far I tried something but the problem is I am not able to get the complete object when I try to print it and Secondly I don't know if there is any way to update an abject and save it back to the set... Here is my code Signal Class (Signal.java)

public class Signal implements Comparable<Signal>{

   String source;
   String name;
   int occurance;

   public void setSource(String source){
       this.source = source;
   }

   public void setName(String name){
       this.name = name;
   }

   public void setOccurance(int occurance){
       this.occurance = occurance;
   }


   public String getSource(){
       return this.source;
   }

   public String getName(){
       return this.name;
   }

   public int getOccurnace(){
       return this.occurance;
   }

@Override
public int compareTo(Signal arg0) {
    // TODO Auto-generated method stub
    return 0;
}
}

My Main Class

  public class SortedSetTest {

   public static void main(String[] args) {

      // Create the sorted set
      SortedSet<Signal> set = new TreeSet<Signal>();

      //Create a Signal object for each new signal
      Signal sig = new Signal();

      sig.setSource("Source");
      sig.setName("Signal Name");
      sig.setOccurance(1);

      // Add elements to the set
      set.add(sig);
      System.out.println(set); 

The above print show me as object...How Can I see the set as String?

      // Iterating over the elements in the set
      Iterator<Signal> it = set.iterator();
      while (it.hasNext()){

Here I want to print each object For example take the first object and print the object (Signal) Source, Name and occurance and so on till the end of the set reaches.
} } }


Solution

  • The lines you're looking for:

        while (it.hasNext()){
            Signal sig = (Signal)it.next();
            System.out.println(sig.getName());
            System.out.println(sig.getOccurance());
            // do the same with source or whatever property 
        }