SHARE
TWEET

tree

DulcetAirman Nov 13th, 2018 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin.foo;
  2.  
  3. import java.util.*;
  4.  
  5. public class SomeClass implements Comparable<SomeClass> {
  6.  
  7.     private static Comparator<SomeClass> COMPARATOR = Comparator.comparing(SomeClass::getCode).thenComparing(SomeClass::getName);
  8.    
  9.     private final String name, code;
  10.     private final NavigableSet<SomeClass> children = new TreeSet<SomeClass>();
  11.     private final SomeClass parent;
  12.  
  13.     // doesn't have to be public. only factory needs access.
  14.     SomeClass(SomeClass parent, String name, String code) {
  15.         this.parent = parent;
  16.         this.name = name;
  17.         this.code = code;
  18.  
  19.     }
  20.  
  21.     // Creates a root
  22.     SomeClass(String name, String code) {
  23.         this(null, name, code);
  24.     }
  25.  
  26.     // doesn't have to be public. only factory needs access.
  27.     void addChild(SomeClass child) {
  28.         this.children.add(child);
  29.     }
  30.  
  31.     public NavigableSet<SomeClass> getChildren() {
  32.         return new TreeSet<>(this.children); // return defensive copy
  33.     }
  34.  
  35.     public Optional<SomeClass> getParent() {
  36.         return Optional.ofNullable(this.parent);
  37.     }
  38.    
  39.     public String getName() {
  40.         return name;
  41.     }
  42.    
  43.     public String getCode() {
  44.         return code;
  45.     }
  46.  
  47.     @Override
  48.     public int compareTo(SomeClass o) {
  49.         return COMPARATOR.compare(this, o);
  50.     }
  51.  
  52. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top