2015-09-07 11:44:36 -06:00
|
|
|
// references/Snake.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Tests cloning to see if reference
|
|
|
|
// destinations are also cloned
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
public class Snake implements Cloneable {
|
|
|
|
private Snake next;
|
|
|
|
private char c;
|
|
|
|
// Value of i == number of segments
|
|
|
|
public Snake(int i, char x) {
|
|
|
|
c = x;
|
|
|
|
if(--i > 0)
|
|
|
|
next = new Snake(i, (char)(x + 1));
|
|
|
|
}
|
|
|
|
public void increment() {
|
|
|
|
c++;
|
|
|
|
if(next != null)
|
|
|
|
next.increment();
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
String s = ":" + c;
|
|
|
|
if(next != null)
|
|
|
|
s += next.toString();
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
@Override
|
2016-01-25 18:05:55 -08:00
|
|
|
public Snake clone() {
|
2015-06-15 17:47:35 -07:00
|
|
|
try {
|
2016-01-25 18:05:55 -08:00
|
|
|
return (Snake)super.clone();
|
2015-06-15 17:47:35 -07:00
|
|
|
} catch(CloneNotSupportedException e) {
|
2016-01-25 18:05:55 -08:00
|
|
|
throw new RuntimeException(e);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Snake s = new Snake(5, 'a');
|
|
|
|
System.out.println("s = " + s);
|
2016-01-25 18:05:55 -08:00
|
|
|
Snake s2 = s.clone();
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println("s2 = " + s2);
|
|
|
|
s.increment();
|
2016-01-25 18:05:55 -08:00
|
|
|
System.out.println("after s.increment, s2 = " + s2);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
s = :a:b:c:d:e
|
|
|
|
s2 = :a:b:c:d:e
|
|
|
|
after s.increment, s2 = :a:c:d:e:f
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|