What is the direct way to copy joda LocalTime?

I need a new instance which is a copy. I could create an instance from integers, but it seems that there should be a more direct way. I could also use some kind of approach like copy = original.minus(zero) , but this is also indirect.

The LocalTime constructor that takes a Java Object argument (for which I used the original LocalTime) does not work. I think it just does not support.

  LocalTime start = new LocalTime(9, 0, 0); LocalTime stop = new LocalTime(17, 0, 0); //LocalTime time = start.minusSeconds(0); // GOOD VERSION LocalTime time = new LocalTime(start); // THE BAD VERSION assert time == start: "does not work"; // EXTRANEOUS STUFF TO JUSTIFY COPYING AN IMMUTABLE, FOLLOWS... while (time.compareTo(stop) <= 0) { //method(time, new LocalTime(9, 0, 0), stop); // MESSY method(time, start, stop); // NICER time = time.plusMinutes(1); } 

I also tried copy = new LocalTime(original.getLocalMillis()) , but I do not have access to getLocalMillis as it is protected.

+4
source share
2 answers

LocalTime is unchanged, so there is no room for two instances with the same value. They can be shared (even across streams). Mutation methods, for example, plus / minus will return a new value, so you can create your copy "on demand" when you need a modified value.

 LocalTime start = new LocalTime(9, 0, 0); LocalTime stop = new LocalTime(17, 0, 0); LocalTime time = start; // Just use the reference while (time.compareTo(stop) <= 0) { method(time, start, stop); time = time.plusMinutes(1); } 
+6
source

This works fine for me:

 LocalTime t1 = new LocalTime(); try { // Sleep for a bit just to make sure the current system time moves on Thread.sleep(5000); } catch (InterruptedException e) { } LocalTime t2 = new LocalTime(t1); assertEquals(t1, t2); 

Pay attention to the second line - I think what you are looking for. t2 gets the same time in milliseconds since an era like t1 .

So, what do you mean when you say that the copy constructor (which I used OK above) doesn’t work?

-1
source

All Articles