├── README.md ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── effectivejava │ │ └── examples │ │ ├── allinone │ │ ├── BlockingList.java │ │ ├── CalculateItems.java │ │ ├── ConcurrentMapUtil.java │ │ ├── Deadlock.java │ │ ├── Flexible.java │ │ ├── Flight.java │ │ ├── KeepItSimple.java │ │ ├── MoneyUtil.java │ │ ├── StaticFactoryExamples.java │ │ ├── StringPerformance.java │ │ ├── StringsAreNotGood.java │ │ └── TelefonRehberi.java │ │ ├── chapter02 │ │ ├── item01 │ │ │ ├── Provider.java │ │ │ ├── Service.java │ │ │ ├── Services.java │ │ │ └── Test.java │ │ ├── item02 │ │ │ └── kodcu │ │ │ │ ├── builder │ │ │ │ ├── NutritionFacts.java │ │ │ │ └── Serum.java │ │ │ │ ├── constructor │ │ │ │ ├── javabeans │ │ │ │ ├── NutritionFacts.java │ │ │ │ └── Serum.java │ │ │ │ └── questions │ │ │ │ └── Serum.java │ │ ├── item03 │ │ │ └── kodcu │ │ │ │ ├── enumoration │ │ │ │ └── Pencil.java │ │ │ │ ├── field │ │ │ │ └── Pencil.java │ │ │ │ ├── method │ │ │ │ └── Pencil.java │ │ │ │ └── questions │ │ │ │ └── Pencil.java │ │ ├── item04 │ │ │ ├── Kitap.java │ │ │ └── UtilityClass.java │ │ ├── item05 │ │ │ └── kodcu │ │ │ │ ├── fastversion │ │ │ │ └── Calisan.java │ │ │ │ ├── questions │ │ │ │ ├── StringQuestion.java │ │ │ │ └── Toplam.java │ │ │ │ └── slowversion │ │ │ │ └── Calisan.java │ │ ├── item06 │ │ │ ├── EmptyStackException.java │ │ │ ├── Stack.java │ │ │ └── Yigin.java │ │ └── trycatch │ │ │ ├── Read.java │ │ │ ├── ReadV2.java │ │ │ ├── ReadV3.java │ │ │ ├── ReadV4.java │ │ │ └── ReadV5.java │ │ ├── chapter03 │ │ ├── item08 │ │ │ ├── CaseInsensitiveString.java │ │ │ ├── Color.java │ │ │ ├── ColorPoint.java │ │ │ ├── CounterPoint.java │ │ │ ├── CounterPointTest.java │ │ │ ├── Point.java │ │ │ └── composition │ │ │ │ ├── Color.java │ │ │ │ ├── ColorPoint.java │ │ │ │ └── Point.java │ │ ├── item09 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ └── TelefonRehberiFixed.java │ │ │ │ └── questions │ │ │ │ └── TelefonRehberi.java │ │ ├── item10 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ └── TelefonRehberiFixed.java │ │ │ │ └── questions │ │ │ │ └── TelefonRehberi.java │ │ ├── item11 │ │ │ ├── EmptyStackException.java │ │ │ ├── PhoneNumber.java │ │ │ └── Stack.java │ │ └── item12 │ │ │ └── kodcu │ │ │ ├── fixed │ │ │ └── PhoneNumber.java │ │ │ └── questions │ │ │ ├── TelefonNumarasi.java │ │ │ └── WordList.java │ │ ├── chapter04 │ │ ├── Item20 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ ├── Circle.java │ │ │ │ ├── Figure.java │ │ │ │ ├── Rectangle.java │ │ │ │ └── Square.java │ │ │ │ └── questions │ │ │ │ └── Math.java │ │ ├── item14 │ │ │ ├── Point.java │ │ │ └── Time.java │ │ ├── item15 │ │ │ └── Complex.java │ │ ├── item16 │ │ │ └── kodcu │ │ │ │ └── questions │ │ │ │ └── MyHashSet.java │ │ ├── item17 │ │ │ └── kodcu │ │ │ │ └── questions │ │ │ │ ├── Ast.java │ │ │ │ └── Super.java │ │ ├── item18 │ │ │ ├── AbstractMapEntry.java │ │ │ └── IntArrays.java │ │ └── item19 │ │ │ └── kodcu │ │ │ ├── fixed │ │ │ └── PhysicalConstants.java │ │ │ └── questions │ │ │ └── IPhysicalConstants.java │ │ ├── chapter05 │ │ ├── item23 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ ├── Raw.java │ │ │ │ └── TypeShowCase.java │ │ │ │ └── questions │ │ │ │ └── KahveDukkani.java │ │ ├── item25 │ │ │ └── kodcu │ │ │ │ └── questions │ │ │ │ ├── Function.java │ │ │ │ ├── Main.java │ │ │ │ └── Reduction.java │ │ ├── item26 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ ├── firsttechnqiue │ │ │ │ │ ├── EmptyStackException.java │ │ │ │ │ └── Stack.java │ │ │ │ └── secondtechnqiue │ │ │ │ │ ├── EmptyStackException.java │ │ │ │ │ └── Stack.java │ │ │ │ └── questions │ │ │ │ └── Stack.java │ │ ├── item27 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ └── Union.java │ │ │ │ └── questions │ │ │ │ └── KelimeBirlestirmece.java │ │ └── item28 │ │ │ └── kodcu │ │ │ ├── fixed │ │ │ └── ParkInnFixed.java │ │ │ └── questions │ │ │ └── ParkInn.java │ │ ├── chapter06 │ │ ├── item30 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ ├── Planet.java │ │ │ │ └── WeightTable.java │ │ │ │ └── questions │ │ │ │ └── Bordro.java │ │ ├── item31 │ │ │ └── Ensemble.java │ │ ├── item32 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ └── Text.java │ │ │ │ └── questions │ │ │ │ └── Metin.java │ │ ├── item33 │ │ │ ├── Herb.java │ │ │ └── Phase.java │ │ ├── item34 │ │ │ ├── BasicOperation.java │ │ │ ├── ExtendedOperation.java │ │ │ └── Operation.java │ │ ├── item36 │ │ │ └── Bigram.java │ │ └── third │ │ │ └── item39 │ │ │ ├── ExceptionTest.java │ │ │ ├── RunTests.java │ │ │ ├── RunTests2.java │ │ │ ├── Sample.java │ │ │ ├── Sample2.java │ │ │ └── Test.java │ │ ├── chapter07 │ │ ├── item39 │ │ │ └── kodcu │ │ │ │ └── fixed │ │ │ │ ├── Attack.java │ │ │ │ └── Period.java │ │ ├── item41 │ │ │ └── kodcu │ │ │ │ └── questions │ │ │ │ ├── Overriding.java │ │ │ │ └── SetList.java │ │ ├── item42 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ └── Varargs.java │ │ │ │ └── questions │ │ │ │ └── Varargs.java │ │ ├── item43 │ │ │ └── kodcu │ │ │ │ ├── fixed │ │ │ │ ├── Cheese.java │ │ │ │ └── Factory.java │ │ │ │ └── questions │ │ │ │ ├── Peynir.java │ │ │ │ └── PeynirFabrikasi.java │ │ ├── item49 │ │ │ ├── BrokenComparator.java │ │ │ └── Unbelievable.java │ │ └── item53 │ │ │ └── MakeSet.java │ │ ├── chapter08 │ │ ├── item46 │ │ │ └── kodcu │ │ │ │ └── LordOfTheLoops.java │ │ ├── item47 │ │ │ └── RandomBug.java │ │ └── item48 │ │ │ └── Candy.java │ │ ├── chapter10 │ │ ├── item66 │ │ │ ├── brokenstopthread │ │ │ │ └── StopThread.java │ │ │ ├── fixedstopthread1 │ │ │ │ └── StopThread.java │ │ │ ├── fixedstopthread2 │ │ │ │ └── StopThread.java │ │ │ └── fixedstopthread3 │ │ │ │ └── StopThread.java │ │ ├── item67 │ │ │ ├── ForwardingSet.java │ │ │ ├── ObservableSet.java │ │ │ ├── SetObserver.java │ │ │ ├── Test1.java │ │ │ ├── Test2.java │ │ │ └── Test3.java │ │ ├── item69 │ │ │ ├── ConcurrentTimer.java │ │ │ └── Intern.java │ │ ├── item71 │ │ │ └── Initialization.java │ │ └── item72 │ │ │ └── SlowCountDownLatch.java │ │ ├── chapter11 │ │ ├── item74 │ │ │ ├── AbstractFoo.java │ │ │ └── Foo.java │ │ ├── item75 │ │ │ └── StringList.java │ │ ├── item76 │ │ │ ├── BogusPeriod.java │ │ │ ├── MutablePeriod.java │ │ │ └── Period.java │ │ ├── item77 │ │ │ ├── Elvis.java │ │ │ ├── ElvisImpersonator.java │ │ │ ├── ElvisStealer.java │ │ │ └── enumSingleton │ │ │ │ └── Elvis.java │ │ └── item78 │ │ │ ├── BogusPeriod.java │ │ │ ├── MutablePeriod.java │ │ │ └── Period.java │ │ ├── exceptions │ │ ├── AccoutingException.java │ │ ├── CustomerDepartureInformation.java │ │ ├── CustomerDepartureInformationV2.java │ │ ├── CustomerDepartureInformationV3.java │ │ ├── CustomerDepartureInformationV4.java │ │ ├── MonthUtil.java │ │ ├── MonthUtilV2.java │ │ ├── ParseUtil.java │ │ ├── SpeedTest.java │ │ └── state │ │ │ ├── App.java │ │ │ ├── SeatEmptyState.java │ │ │ ├── SeatIsFullState.java │ │ │ ├── SeatSales.java │ │ │ └── State.java │ │ ├── lambda │ │ └── Order.java │ │ ├── optional │ │ ├── AramaTarama.java │ │ └── AramaTarama2.java │ │ ├── serialize │ │ ├── Calisan.java │ │ ├── Okuyucu.java │ │ └── Yazici.java │ │ └── streams │ │ ├── AnagramsV1.java │ │ ├── AnagramsV2.java │ │ ├── ParallelV1.java │ │ ├── ParallelV2.java │ │ ├── ParallelV3.java │ │ └── StreamSum.java └── resources │ ├── gridlock.gif │ ├── naming_conventions.png │ └── stream_performance_image1.png └── test └── java ├── org └── effectivejava │ └── examples │ └── AppTest.java └── state └── SeatSalesTest.java /README.md: -------------------------------------------------------------------------------- 1 | # Effective Java Örnekleri 2 | 3 | http://www.oracle.com/technetwork/articles/java/bloch-effective-08-qa-140880.html 4 | 5 | 6 | 7 | # coreeffectivejava 8 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | effective-java-examples 5 | effective-java-examples 6 | 1.0 7 | effective-java-examples 8 | Source code to the book "Effective Java Second Edition" created by Joshua Bloch 9 | http://java.sun.com/docs/books/effective/index.html 10 | 11 | Joshua Bloch 12 | http://java.sun.com/docs/books/effective/index.html 13 | 14 | 15 | 16 | junit 17 | junit 18 | 4.12 19 | test 20 | 21 | 22 | 23 | org.slf4j 24 | slf4j-api 25 | 1.7.21 26 | 27 | 28 | 29 | ch.qos.logback 30 | logback-classic 31 | 1.1.7 32 | 33 | 34 | com.google.guava 35 | guava 36 | 24.1-jre 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | maven-compiler-plugin 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/BlockingList.java: -------------------------------------------------------------------------------- 1 | // ITEM 81 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Queue; 7 | 8 | 9 | public class BlockingList { 10 | 11 | /* 12 | * 13 | * 1 - If you use LinkedList, ArrayList ... then synchronization is your responsibility 14 | * 2 - Always use the wait inside a loop; 15 | */ 16 | 17 | private Queue queue = new LinkedList<>(); 18 | private int capacity; 19 | 20 | public BlockingList(int capacity) { 21 | this.capacity = capacity; 22 | } 23 | 24 | public synchronized void put(T element) throws InterruptedException { 25 | while(queue.size() == capacity) { 26 | /* 27 | Always use the wait inside a loop; 28 | */ 29 | wait(); 30 | } 31 | 32 | queue.add(element); 33 | notify(); // 3 - notifyAll() for multiple producer/consumer threads 34 | } 35 | 36 | public synchronized T take() throws InterruptedException { 37 | while(queue.isEmpty()) { 38 | /* 39 | Always use the wait inside a loop; 40 | */ 41 | wait(); 42 | } 43 | 44 | T item = queue.remove(); 45 | notify(); // notifyAll() for multiple producer/consumer threads 46 | return item; 47 | 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/CalculateItems.java: -------------------------------------------------------------------------------- 1 | // ITEM 82 2 | package org.effectivejava.examples.allinone; 3 | 4 | import javax.annotation.concurrent.Immutable; 5 | import javax.annotation.concurrent.NotThreadSafe; 6 | import java.util.Collections; 7 | import java.util.HashMap; 8 | 9 | @NotThreadSafe 10 | @Immutable 11 | public class CalculateItems { 12 | 13 | private final int key; 14 | private final int value; 15 | 16 | public CalculateItems(int key, int value) { 17 | this.key = key; 18 | this.value = value; 19 | } 20 | // TODO : what makes thread safe ? 21 | public void process() { 22 | // ... 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/ConcurrentMapUtil.java: -------------------------------------------------------------------------------- 1 | // ITEM 81 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.Collections; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | import java.util.concurrent.ConcurrentMap; 7 | 8 | public class ConcurrentMapUtil { 9 | 10 | /** 11 | * 12 | * 1 - Prefer ConcurrentHashMap instead of using Collections.synchronizedMap 13 | * 1.1 - Difference between Hashtable and ConcurrentHashMap ?? 14 | * 2 - Always use System.nanoTime(); 15 | */ 16 | 17 | 18 | /** 19 | * 20 | * 3 - Simply replacing synchronized maps with concurrent maps can 21 | * dramatically increase the performance of concurrent applications. 22 | */ 23 | private static final ConcurrentMap map = 24 | new ConcurrentHashMap<>(); 25 | 26 | // Concurrent canonicalizing map atop ConcurrentMap - not optimal 27 | public static String find(String s) { 28 | String previousValue = map.putIfAbsent(s, s); 29 | return previousValue == null ? s : previousValue; 30 | 31 | } 32 | 33 | 34 | // Concurrent canonicalizing map atop ConcurrentMap - faster! 35 | public static String effectiveFind(String s) { 36 | String result = map.get(s); // is optimized for retrieval get 37 | if (result == null) { 38 | result = map.putIfAbsent(s, s); 39 | if (result == null) 40 | result = s; 41 | } 42 | return result; 43 | } 44 | 45 | public static void main(String[] args) { 46 | long start = System.nanoTime(); // 2- Always use System.nanoTime(); 47 | for (int i = 0; i < 1; i++) { 48 | String result = effectiveFind("hello"); 49 | } 50 | long stop = System.nanoTime(); // 2- Always use System.nanoTime(); 51 | System.err.println("" + ((stop - start) / 1000000000.0)); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/Deadlock.java: -------------------------------------------------------------------------------- 1 | // ITEM 79 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.Hashtable; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | 7 | public class Deadlock { 8 | 9 | /* 10 | 11 | 1- keep the amount of work that you do from within synchronized regions to a minimum. 12 | 2- When you are designing a mutable class, think about whether it should do its own synchronization. 13 | 3 - In the ulticore era, it is more important than ever not to oversynchronize. 14 | 4 - Synchronize our class internally only if there is a good reason to do so, and document your 15 | decision @ThreadSafe 16 | 17 | */ 18 | public static void main(String[] args) { 19 | // These are the two resource objects we'll try to get locks for 20 | final Object resource1 = "resource1"; 21 | final Object resource2 = "resource2"; 22 | // Here's the first thread. It tries to lock resource1 then resource2 23 | Thread t1 = new Thread() { 24 | public void run() { 25 | // Lock resource 1 26 | synchronized(resource1) { 27 | System.out.println("Thread 1: locked resource 1"); 28 | 29 | // Pause for a bit, simulating some file I/O or something. 30 | // Basically, we just want to give the other thread a chance to 31 | // run. Threads and deadlock are asynchronous things, but we're 32 | // trying to force deadlock to happen here... 33 | try { Thread.sleep(50); } catch (InterruptedException e) {} 34 | 35 | // Now wait 'till we can get a lock on resource 2 36 | synchronized(resource2) { 37 | System.out.println("Thread 1: locked resource 2"); 38 | } 39 | } 40 | } 41 | }; 42 | 43 | // Here's the second thread. It tries to lock resource2 then resource1 44 | Thread t2 = new Thread() { 45 | public void run() { 46 | // This thread locks resource 2 right away 47 | synchronized(resource2) { 48 | System.out.println("Thread 2: locked resource 2"); 49 | 50 | // Then it pauses, for the same reason as the first thread does 51 | try { Thread.sleep(50); } catch (InterruptedException e) {} 52 | 53 | // Then it tries to lock resource1. But wait! Thread 1 locked 54 | // resource1, and won't release it 'till it gets a lock on 55 | // resource2. This thread holds the lock on resource2, and won't 56 | // release it 'till it gets resource1. We're at an impasse. Neither 57 | // thread can run, and the program freezes up. 58 | synchronized(resource1) { 59 | System.out.println("Thread 2: locked resource 1"); 60 | } 61 | } 62 | } 63 | }; 64 | 65 | // Start the two threads. If all goes as planned, deadlock will occur, 66 | // and the program will never exit. 67 | t1.start(); 68 | t2.start(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/Flexible.java: -------------------------------------------------------------------------------- 1 | // ITEM 64 2 | package org.effectivejava.examples.allinone; 3 | 4 | import org.effectivejava.examples.exceptions.CustomerDepartureInformation; 5 | 6 | import java.util.*; 7 | 8 | public class Flexible { 9 | // Good - uses interface as type 10 | List customerDepartureInformationList = new LinkedList<>(); 11 | 12 | // Bad - uses class as type! 13 | LinkedList badReferenceList = new LinkedList<>(); 14 | 15 | public Flexible() { 16 | 17 | // If you get into the habit of using interfaces as types, your program will be 18 | //much more flexible. 19 | customerDepartureInformationList =new ArrayList<>(); 20 | } 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/Flight.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.allinone; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.stream.Stream; 7 | 8 | 9 | class Flight 10 | { 11 | private List customers = new ArrayList<>(); 12 | 13 | // this one ? 14 | public List getCustomers() { 15 | return Collections.unmodifiableList(customers); 16 | } 17 | 18 | // this one ? 19 | public Stream getCustomerStream() 20 | { 21 | return customers.stream(); 22 | } 23 | 24 | } 25 | 26 | class Customer { 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/KeepItSimple.java: -------------------------------------------------------------------------------- 1 | // ITEM 57 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.Arrays; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | 8 | public class KeepItSimple { 9 | 10 | static List c = Arrays.asList("Antalya", "Izmir" , "Sinop") ; 11 | 12 | static List c2 = Arrays.asList("Kagithane", "Istoc" , "Findikli") ; 13 | 14 | public static void calculate() { 15 | 16 | Iterator i = c.iterator(); 17 | while (i.hasNext()) { 18 | System.out.println(i.next()); 19 | } 20 | 21 | // ..... 22 | 23 | Iterator i2 = c2.iterator(); 24 | while (i.hasNext()) { 25 | System.out.println(i2.next()); 26 | } 27 | } 28 | 29 | 30 | 31 | 32 | public static void main(String[] args) { 33 | calculate(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/MoneyUtil.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.allinone; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class MoneyUtil { 6 | 7 | /** 8 | * Returns a BigInteger whose value is (this mod m). This method 9 | * differs from the remainder method in that it always returns a 10 | * non-negative BigInteger. 11 | * 12 | * @param m the modulus, which must be positive 13 | * @return this mod m 14 | * @throws ArithmeticException if m is less than or equal to 0 15 | */ 16 | public BigInteger mod(BigInteger m) { 17 | if (m.signum() <= 0) 18 | throw new ArithmeticException("Modulus <= 0: " + m); 19 | 20 | // Do the computation 21 | 22 | return BigInteger.ONE; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/StaticFactoryExamples.java: -------------------------------------------------------------------------------- 1 | // ITEM 1 2 | package org.effectivejava.examples.allinone; 3 | 4 | import org.effectivejava.examples.chapter04.item18.AbstractMapEntry; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.lang.reflect.Array; 9 | import java.math.BigInteger; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.Paths; 13 | import java.time.Instant; 14 | import java.util.AbstractCollection; 15 | import java.util.Date; 16 | import java.util.EnumSet; 17 | 18 | public class StaticFactoryExamples { 19 | 20 | public static void main(String[] args) throws IOException { 21 | 22 | 23 | /** 24 | * Often static factories are preferable 25 | * 26 | * so avoid the reflex to provide 27 | * public constructors without first considering 28 | * static factories. 29 | */ 30 | Date d = Date.from(Instant.now()); 31 | 32 | // Set faceCards = EnumSet.of(JACK, QUEEN, KING); 33 | 34 | BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE); 35 | 36 | Date[] dates = (Date[]) Array.newInstance(Date.class, 1); 37 | 38 | Path logFile = Paths.get("/temp/logs/app.log"); 39 | BufferedReader br = Files.newBufferedReader(logFile); 40 | 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/StringPerformance.java: -------------------------------------------------------------------------------- 1 | // ITEM 63 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.concurrent.ThreadLocalRandom; 5 | 6 | public class StringPerformance { 7 | 8 | // Inappropriate use of string concatenation - Performs poorly! 9 | public String statement() { 10 | String result = ""; 11 | for (int i = 0; i < numItems(); i++) 12 | result += lineForItem(); // String concatenation 13 | return result; 14 | } 15 | 16 | 17 | public String statementWithStringBuilder() { 18 | StringBuilder b = new StringBuilder(); 19 | for (int i = 0; i < numItems(); i++) 20 | b.append(lineForItem()); 21 | return b.toString(); 22 | } 23 | 24 | private char lineForItem() { 25 | char c = (char)(ThreadLocalRandom.current().nextInt(26) + 'a'); 26 | return c; 27 | } 28 | 29 | private int numItems() { 30 | return 100; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/StringsAreNotGood.java: -------------------------------------------------------------------------------- 1 | // ITEM 62 2 | package org.effectivejava.examples.allinone; 3 | 4 | import java.util.concurrent.ThreadLocalRandom; 5 | 6 | public class StringsAreNotGood { 7 | 8 | ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current(); 9 | public StringsAreNotGood() { 10 | 11 | // not good, be specific 12 | String compoundKey = this.getClass().getName() + "#" + threadLocalRandom.nextInt(); 13 | } 14 | 15 | } 16 | 17 | 18 | class DataLocal { 19 | private DataLocal() { } // Noninstantiable 20 | // Sets the current datalocal's value for the named variable. 21 | public static void set(String key, Object value) {}; 22 | // Returns the current datalocal's value for the named variable. 23 | public static Object get(String key){ return new Object();}; 24 | } 25 | 26 | 27 | // string-based API problem solved 28 | class DataLocal2 { 29 | private DataLocal2() { } // Noninstantiable 30 | public static class Key { // (Capability) 31 | private int value; 32 | Key() { } 33 | public void setValue(int value) { this.value = value;} 34 | } 35 | // Generates a unique, unforgeable key 36 | public static Key getKey() { 37 | return new Key(); 38 | } 39 | public static void set(Key key, Object value){}; 40 | public static Object get(Key key){return new Object();}; 41 | } 42 | 43 | final class DataLocal3 { 44 | private T value ; 45 | public DataLocal3(){}; 46 | public void set(T value){}; 47 | public T get(){ return value ; }; 48 | 49 | 50 | } 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/allinone/TelefonRehberi.java: -------------------------------------------------------------------------------- 1 | // ITEM 40 2 | package org.effectivejava.examples.allinone; 3 | 4 | 5 | 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | // Can you spot the bug? 11 | public final class TelefonRehberi { 12 | private final short alanKod; 13 | private final short prefix; 14 | private final short numara; 15 | 16 | public TelefonRehberi(int alanKod, int prefix, int numara) { 17 | kontrol(alanKod, 999, "alan kod"); 18 | kontrol(prefix, 999, "prefix"); 19 | kontrol(numara, 9999, "numara"); 20 | this.alanKod = (short) alanKod; 21 | this.prefix = (short) prefix; 22 | this.numara = (short) numara; 23 | } 24 | 25 | private static void kontrol(int arg, int max, String name) { 26 | if (arg < 0 || arg > max) 27 | throw new IllegalArgumentException(name + ": " + arg); 28 | } 29 | 30 | 31 | public boolean equals(TelefonRehberi o) { 32 | if (o == this) 33 | return true; 34 | if (!(o instanceof TelefonRehberi)) 35 | return false; 36 | 37 | return o.numara == numara && o.prefix == prefix 38 | && o.alanKod == alanKod; 39 | } 40 | 41 | 42 | 43 | public int hashCode() { 44 | int result = 17; 45 | result = 31 * result + alanKod; 46 | result = 31 * result + prefix; 47 | result = 31 * result + numara; 48 | return result; 49 | } 50 | 51 | 52 | 53 | public static void main(String[] args) { 54 | Map m = new HashMap(); 55 | m.put(new TelefonRehberi(707, 867, 5309), "Ayse"); 56 | System.out.println(m.get(new TelefonRehberi(707, 867, 5309))); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item01/Provider.java: -------------------------------------------------------------------------------- 1 | // Service provider framework sketch - Service provider interface - Page 12 2 | package org.effectivejava.examples.chapter02.item01; 3 | 4 | public interface Provider { 5 | Service newService(); 6 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item01/Service.java: -------------------------------------------------------------------------------- 1 | // Service provider framework sketch - Service interface - Page 12 2 | package org.effectivejava.examples.chapter02.item01; 3 | 4 | public interface Service { 5 | // Service-specific methods go here 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item01/Services.java: -------------------------------------------------------------------------------- 1 | // Service provider framework sketch 2 | 3 | // Noninstantiable class for service registration and access - Pages 8-9 4 | package org.effectivejava.examples.chapter02.item01; 5 | 6 | import java.util.Map; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | 9 | public class Services { 10 | private Services() { 11 | } // Prevents instantiation (Item 4) 12 | 13 | // Maps service names to services 14 | private static final Map providers = new ConcurrentHashMap(); 15 | public static final String DEFAULT_PROVIDER_NAME = ""; 16 | 17 | // Provider registration API 18 | public static void registerDefaultProvider(Provider p) { 19 | registerProvider(DEFAULT_PROVIDER_NAME, p); 20 | } 21 | 22 | public static void registerProvider(String name, Provider p) { 23 | providers.put(name, p); 24 | } 25 | 26 | // Service access API 27 | public static Service newInstance() { 28 | return newInstance(DEFAULT_PROVIDER_NAME); 29 | } 30 | 31 | public static Service newInstance(String name) { 32 | Provider p = providers.get(name); 33 | if (p == null) 34 | throw new IllegalArgumentException( 35 | "No provider registered with name: " + name); 36 | return p.newService(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item01/Test.java: -------------------------------------------------------------------------------- 1 | // Simple test program for service provider framework 2 | package org.effectivejava.examples.chapter02.item01; 3 | 4 | public class Test { 5 | public static void main(String[] args) { 6 | // Providers would execute these lines 7 | Services.registerDefaultProvider(DEFAULT_PROVIDER); 8 | Services.registerProvider("comp", COMP_PROVIDER); 9 | Services.registerProvider("armed", ARMED_PROVIDER); 10 | 11 | // Clients would execute these lines 12 | Service s1 = Services.newInstance(); 13 | Service s2 = Services.newInstance("comp"); 14 | Service s3 = Services.newInstance("armed"); 15 | System.out.printf("%s, %s, %s%n", s1, s2, s3); 16 | } 17 | 18 | private static Provider DEFAULT_PROVIDER = new Provider() { 19 | public Service newService() { 20 | return new Service() { 21 | @Override 22 | public String toString() { 23 | return "Default service"; 24 | } 25 | }; 26 | } 27 | }; 28 | 29 | private static Provider COMP_PROVIDER = new Provider() { 30 | public Service newService() { 31 | return new Service() { 32 | @Override 33 | public String toString() { 34 | return "Complementary service"; 35 | } 36 | }; 37 | } 38 | }; 39 | 40 | private static Provider ARMED_PROVIDER = new Provider() { 41 | public Service newService() { 42 | return new Service() { 43 | @Override 44 | public String toString() { 45 | return "Armed service"; 46 | } 47 | }; 48 | } 49 | }; 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/builder/NutritionFacts.java: -------------------------------------------------------------------------------- 1 | // Builder Pattern - Pages 14-15 2 | package org.effectivejava.examples.chapter02.item02.kodcu.builder; 3 | 4 | public class NutritionFacts { 5 | private final int servingSize; 6 | private final int servings; 7 | private final int calories; 8 | private final int fat; 9 | private final int sodium; 10 | private final int carbohydrate; 11 | 12 | public static class Builder { 13 | // Required parameters 14 | private final int servingSize; 15 | private final int servings; 16 | 17 | // Optional parameters - initialized to default values 18 | private int calories = 0; 19 | private int fat = 0; 20 | private int carbohydrate = 0; 21 | private int sodium = 0; 22 | 23 | public Builder(int servingSize, int servings) { 24 | this.servingSize = servingSize; 25 | this.servings = servings; 26 | } 27 | 28 | public Builder calories(int val) { 29 | calories = val; 30 | return this; 31 | } 32 | 33 | public Builder fat(int val) { 34 | fat = val; 35 | return this; 36 | } 37 | 38 | public Builder carbohydrate(int val) { 39 | carbohydrate = val; 40 | return this; 41 | } 42 | 43 | public Builder sodium(int val) { 44 | sodium = val; 45 | return this; 46 | } 47 | 48 | public NutritionFacts build() { 49 | return new NutritionFacts(this); 50 | } 51 | } 52 | 53 | private NutritionFacts(Builder builder) { 54 | servingSize = builder.servingSize; 55 | servings = builder.servings; 56 | calories = builder.calories; 57 | fat = builder.fat; 58 | sodium = builder.sodium; 59 | carbohydrate = builder.carbohydrate; 60 | } 61 | 62 | public static void main(String[] args) { 63 | NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) 64 | .calories(100).sodium(35).carbohydrate(27).build(); 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/builder/Serum.java: -------------------------------------------------------------------------------- 1 | // Builder Pattern - Pages 14-15 2 | package org.effectivejava.examples.chapter02.item02.kodcu.builder; 3 | 4 | public class Serum { 5 | private final int water; // required 6 | private final int sodiumIon; // required 7 | private final int magnesium; // optional 8 | private final int creatine; // optional 9 | private final int globulin; // optional 10 | private final int carbohydrate; // optional 11 | 12 | 13 | public static class Builder { 14 | // Required parameters 15 | private final int water; 16 | private final int sodiumIon; 17 | 18 | // Optional parameters - initialized to default values 19 | private int magnesium = 0; 20 | private int creatine = 0; 21 | private int globulin = 0; 22 | private int carbohydrate = 0; 23 | 24 | public Builder(int water, int sodiumIon) { 25 | this.water = water; 26 | this.sodiumIon = sodiumIon; 27 | } 28 | 29 | public Builder magnesium(int val) { 30 | magnesium = val; 31 | return this; 32 | } 33 | 34 | public Builder creatine(int val) { 35 | creatine = val; 36 | return this; 37 | } 38 | 39 | public Builder globulin(int val) { 40 | globulin = val; 41 | return this; 42 | } 43 | 44 | public Builder carbohydrate(int val) { 45 | carbohydrate = val; 46 | return this; 47 | } 48 | 49 | public Serum build() { 50 | return new Serum(this); 51 | } 52 | } 53 | 54 | private Serum(Builder builder) { 55 | water = builder.water; 56 | sodiumIon = builder.sodiumIon; 57 | magnesium = builder.magnesium; 58 | creatine = builder.creatine; 59 | globulin = builder.globulin; 60 | carbohydrate = builder.carbohydrate; 61 | System.out.println("Serum is created"); 62 | } 63 | 64 | public static void main(String[] args) { 65 | Serum typeB = new Serum.Builder(240, 8) 66 | .magnesium(100).creatine(35).globulin(27).build(); 67 | 68 | System.out.println(typeB.carbohydrate); 69 | } 70 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/constructor/NutritionFacts.java: -------------------------------------------------------------------------------- 1 | // Telescoping constructor pattern - does not scale well! - Pages 11-12 2 | package org.effectivejava.examples.chapter02.item02.kodcu.constructor; 3 | 4 | public class NutritionFacts { 5 | private final int servingSize; // (mL) required 6 | private final int servings; // (per container) required 7 | private final int calories; // optional 8 | private final int fat; // (g) optional 9 | private final int sodium; // (mg) optional 10 | private final int carbohydrate; // (g) optional 11 | 12 | public NutritionFacts(int servingSize, int servings) { 13 | this(servingSize, servings, 0); 14 | } 15 | 16 | public NutritionFacts(int servingSize, int servings, int calories) { 17 | this(servingSize, servings, calories, 0); 18 | } 19 | 20 | public NutritionFacts(int servingSize, int servings, int calories, int fat) { 21 | this(servingSize, servings, calories, fat, 0); 22 | } 23 | 24 | public NutritionFacts(int servingSize, int servings, int calories, int fat, 25 | int sodium) { 26 | this(servingSize, servings, calories, fat, sodium, 0); 27 | } 28 | 29 | public NutritionFacts(int servingSize, int servings, int calories, int fat, 30 | int sodium, int carbohydrate) { 31 | this.servingSize = servingSize; 32 | this.servings = servings; 33 | this.calories = calories; 34 | this.fat = fat; 35 | this.sodium = sodium; 36 | this.carbohydrate = carbohydrate; 37 | } 38 | 39 | public static void main(String[] args) { 40 | NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27); 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/constructor/Serum.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.item02.kodcu.constructor; 2 | 3 | public class Serum { 4 | private final int water; // (mL) required 5 | private final int sodiumIon; // required 6 | private final int magnesium; // optional 7 | private final int creatine; // (g) optional 8 | private final int globulin; // (mg) optional 9 | private final int carbohydrate; // (g) optional 10 | 11 | public Serum(int water, int sodiumIon) { 12 | this(water, sodiumIon, 0); 13 | } 14 | 15 | public Serum(int water, int sodiumIon, int magnesium) { 16 | this(water, sodiumIon, magnesium, 0); 17 | } 18 | 19 | public Serum(int water, int sodiumIon, int magnesium, int creatine) { 20 | this(water, sodiumIon, magnesium, creatine, 0); 21 | } 22 | 23 | public Serum(int water, int sodiumIon, int magnesium, int creatine, 24 | int globulin) { 25 | this(water, sodiumIon, magnesium, creatine, globulin, 0); 26 | } 27 | 28 | public Serum(int water, int SodiumIon, int magnesium, int creatine, 29 | int globulin, int carbohydrate) { 30 | this.water = water; 31 | this.sodiumIon = SodiumIon; 32 | this.magnesium = magnesium; 33 | this.creatine = creatine; 34 | this.globulin = globulin; 35 | this.carbohydrate = carbohydrate; 36 | } 37 | 38 | public static void main(String[] args) { 39 | Serum aType = new Serum(240, 8, 100, 0, 35, 27); 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/javabeans/NutritionFacts.java: -------------------------------------------------------------------------------- 1 | // JavaBeans Pattern - allows inconsistency, mandates mutability - Pages 12-13 2 | package org.effectivejava.examples.chapter02.item02.kodcu.javabeans; 3 | 4 | public class NutritionFacts { 5 | // Parameters initialized to default values (if any) 6 | private int servingSize = -1; // Required; no default value 7 | private int servings = -1; // " " " " 8 | private int calories = 0; 9 | private int fat = 0; 10 | private int sodium = 0; 11 | private int carbohydrate = 0; 12 | 13 | public NutritionFacts() { 14 | } 15 | 16 | // Setters 17 | public void setServingSize(int val) { 18 | servingSize = val; 19 | } 20 | 21 | public void setServings(int val) { 22 | servings = val; 23 | } 24 | 25 | public void setCalories(int val) { 26 | calories = val; 27 | } 28 | 29 | public void setFat(int val) { 30 | fat = val; 31 | } 32 | 33 | public void setSodium(int val) { 34 | sodium = val; 35 | } 36 | 37 | public void setCarbohydrate(int val) { 38 | carbohydrate = val; 39 | } 40 | 41 | public static void main(String[] args) { 42 | NutritionFacts cocaCola = new NutritionFacts(); 43 | cocaCola.setServingSize(240); 44 | cocaCola.setServings(8); 45 | cocaCola.setCalories(100); 46 | cocaCola.setSodium(35); 47 | cocaCola.setCarbohydrate(27); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/javabeans/Serum.java: -------------------------------------------------------------------------------- 1 | // JavaBeans Pattern - allows inconsistency, mandates mutability - Pages 12-13 2 | package org.effectivejava.examples.chapter02.item02.kodcu.javabeans; 3 | 4 | public class Serum { 5 | // Parameters initialized to default values (if any) 6 | 7 | private int water = 0; // (mL) required 8 | private int sodiumIon = 0 ; // required 9 | private int magnesium = 0; // optional 10 | private int creatine = 0; // (g) optional 11 | private int globulin = 0; // (mg) optional 12 | private int carbohydrate = 0; // (g) optional 13 | 14 | 15 | public Serum() { 16 | } 17 | 18 | // Setters 19 | 20 | public void setWater(int water) { 21 | this.water = water; 22 | } 23 | 24 | public void setSodiumIon(int sodiumIon) { 25 | this.sodiumIon = sodiumIon; 26 | } 27 | 28 | public void setMagnesium(int magnesium) { 29 | this.magnesium = magnesium; 30 | } 31 | 32 | 33 | public void setCreatine(int creatine) { 34 | this.creatine = creatine; 35 | } 36 | 37 | 38 | public void setGlobulin(int globulin) { 39 | this.globulin = globulin; 40 | } 41 | 42 | 43 | public void setCarbohydrate(int carbohydrate) { 44 | this.carbohydrate = carbohydrate; 45 | } 46 | 47 | public static void main(String[] args) { 48 | Serum typeB = new Serum(); 49 | typeB.setWater(240); 50 | typeB.setSodiumIon(8); 51 | typeB.setMagnesium(100); 52 | typeB.setCreatine(35); 53 | typeB.setCarbohydrate(27); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item02/kodcu/questions/Serum.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.item02.kodcu.questions; 2 | 3 | public class Serum { 4 | private final int water = 0; // (mL) required 5 | private final int sodiumIon = 0 ; // required 6 | private final int magnesium = 0; // optional 7 | private final int creatine = 0; // (g) optional 8 | private final int globulin = 0; // (mg) optional 9 | private final int carbohydrate = 0; // (g) optional 10 | 11 | 12 | 13 | public static void main(String[] args) { 14 | // Create A Serum 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item03/kodcu/enumoration/Pencil.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter02.item03.kodcu.enumoration; 3 | 4 | public enum Pencil { 5 | INSTANCE; // guarantee against multiple instantiation and thread safe for free 6 | 7 | public void write() { 8 | System.out.println("write !"); 9 | } 10 | 11 | 12 | public static void main(String[] args) { 13 | Pencil pencil = Pencil.INSTANCE; 14 | pencil.write(); 15 | 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item03/kodcu/field/Pencil.java: -------------------------------------------------------------------------------- 1 | // Singleton with public final field - Page 17 2 | package org.effectivejava.examples.chapter02.item03.kodcu.field; 3 | 4 | public class Pencil { 5 | public static final Pencil INSTANCE = new Pencil(); 6 | 7 | private Pencil() { 8 | } 9 | 10 | public void justDoIt() { 11 | System.out.println("I'm writing ... "); 12 | } 13 | 14 | // This code would normally appear outside the class! 15 | public static void main(String[] args) { 16 | Pencil pencil = Pencil.INSTANCE; 17 | pencil.justDoIt(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item03/kodcu/method/Pencil.java: -------------------------------------------------------------------------------- 1 | // Singleton with static factory - Page 17 2 | package org.effectivejava.examples.chapter02.item03.kodcu.method; 3 | 4 | public class Pencil { 5 | private static final Pencil INSTANCE = new Pencil(); 6 | 7 | private Pencil() { 8 | } 9 | 10 | public static Pencil getInstance() { // possible multi thread attaks 11 | return INSTANCE; 12 | } 13 | 14 | public void write() { 15 | System.out.println("write !"); 16 | } 17 | 18 | // This code would normally appear outside the class! 19 | public static void main(String[] args) { 20 | Pencil pencil = Pencil.getInstance(); 21 | pencil.write(); 22 | 23 | // method advantage : you can use it in lambda exp 24 | //Pencil::getInstance 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item03/kodcu/questions/Pencil.java: -------------------------------------------------------------------------------- 1 | // Singleton with static factory - Page 17 2 | package org.effectivejava.examples.chapter02.item03.kodcu.questions; 3 | 4 | public class Pencil { 5 | 6 | // make this class in a Singleton way 7 | 8 | public void write() { 9 | System.out.println("Writing!"); 10 | } 11 | 12 | // This code would normally appear outside the class! 13 | public static void main(String[] args) { 14 | Pencil pencil = new Pencil(); 15 | pencil = new Pencil(); // always new object is created, not good 16 | pencil = new Pencil(); // always new object is created, not good 17 | pencil.write(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item04/Kitap.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter02.item04; 3 | 4 | public class Kitap { 5 | 6 | // make Noninstantiable Kitap class 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item04/UtilityClass.java: -------------------------------------------------------------------------------- 1 | // Noninstantiable utility class 2 | package org.effectivejava.examples.chapter02.item04; 3 | 4 | public class UtilityClass { 5 | // Suppress default constructor for noninstantiability 6 | private UtilityClass() { 7 | throw new AssertionError(); // why ? 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item05/kodcu/fastversion/Calisan.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter02.item05.kodcu.fastversion; 3 | 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | import java.util.TimeZone; 7 | 8 | class Calisan { 9 | private final Date birthDate; 10 | 11 | public Calisan(Date birthDate) { 12 | 13 | this.birthDate = new Date(birthDate.getTime()); 14 | } 15 | 16 | // Other fields, methods 17 | 18 | /** 19 | * The starting and ending dates of the baby boom. 20 | */ 21 | private static final Date BOOM_START; 22 | private static final Date BOOM_END; 23 | 24 | static { // key point 25 | Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));// olusturulması maliyetli nesneler 26 | gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0); 27 | BOOM_START = gmtCal.getTime(); 28 | gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0); 29 | BOOM_END = gmtCal.getTime(); 30 | } 31 | 32 | public boolean isBabyBoomer() { 33 | return birthDate.compareTo(BOOM_START) >= 0 34 | && birthDate.compareTo(BOOM_END) < 0; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item05/kodcu/questions/StringQuestion.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.item05.kodcu.questions; 2 | 3 | public class StringQuestion { 4 | 5 | public static void main(String[] args) { 6 | 7 | 8 | String s1 = new String("selam"); 9 | String s2 = "selam"; 10 | String s3 = "selam" ; 11 | 12 | if (s1 == s2) { 13 | System.out.println(" s1 == s2"); 14 | } 15 | 16 | if (s2 == s3) { 17 | System.out.println("s2 == s3"); 18 | } 19 | 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item05/kodcu/questions/Toplam.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.item05.kodcu.questions; 2 | 3 | public class Toplam { 4 | // Hideously slow program! Can you spot the object creation? 5 | public static void main(String[] args) { 6 | Long sum = 0L; 7 | for (long i = 0; i < Integer.MAX_VALUE; i++) { 8 | sum += i; 9 | } 10 | System.out.println(sum); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item05/kodcu/slowversion/Calisan.java: -------------------------------------------------------------------------------- 1 | 2 | //what is wrong in this class ? 3 | package org.effectivejava.examples.chapter02.item05.kodcu.slowversion; 4 | 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.TimeZone; 8 | 9 | public class Calisan { 10 | private final Date birthDate; 11 | 12 | public Calisan(Date birthDate) { 13 | 14 | this.birthDate = new Date(birthDate.getTime()); 15 | } 16 | 17 | 18 | public boolean isBabyBoomer() { 19 | 20 | Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 21 | gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0); 22 | Date boomStart = gmtCal.getTime(); 23 | gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0); 24 | Date boomEnd = gmtCal.getTime(); 25 | return birthDate.compareTo(boomStart) >= 0 26 | && birthDate.compareTo(boomEnd) < 0; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item06/EmptyStackException.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.item06; 2 | 3 | public class EmptyStackException extends IllegalStateException { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item06/Stack.java: -------------------------------------------------------------------------------- 1 | // Can you spot the "memory leak"? 2 | package org.effectivejava.examples.chapter02.item06; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Stack { 7 | private Object[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | public Stack() { 12 | elements = new Object[DEFAULT_INITIAL_CAPACITY]; 13 | } 14 | 15 | public void push(Object e) { 16 | ensureCapacity(); 17 | elements[size++] = e; 18 | } 19 | 20 | public Object pop() { 21 | if (size == 0) 22 | throw new EmptyStackException(); 23 | return elements[--size]; 24 | } 25 | 26 | /** 27 | * Ensure space for at least one more element, roughly doubling the capacity 28 | * each time the array needs to grow. 29 | */ 30 | private void ensureCapacity() { 31 | if (elements.length == size) 32 | elements = Arrays.copyOf(elements, 2 * size + 1); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/item06/Yigin.java: -------------------------------------------------------------------------------- 1 | // Can you spot the "memory leak"? 2 | package org.effectivejava.examples.chapter02.item06; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Yigin { 7 | private Object[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | public Yigin() { 12 | elements = new Object[DEFAULT_INITIAL_CAPACITY]; 13 | } 14 | 15 | public void push(Object e) { 16 | ensureCapacity(); 17 | elements[size++] = e; 18 | } 19 | 20 | public Object pop() { 21 | if (size == 0) 22 | throw new EmptyStackException(); 23 | Object result = elements[--size]; 24 | elements[size] = null ; 25 | return result; 26 | } 27 | 28 | /** 29 | * Ensure space for at least one more element, roughly doubling the capacity 30 | * each time the array needs to grow. 31 | */ 32 | private void ensureCapacity() { 33 | if (elements.length == size) 34 | elements = Arrays.copyOf(elements, 2 * size + 1); 35 | } 36 | 37 | public static void main(String[] args) { 38 | Yigin stack = new Yigin(); 39 | for (long i = 0; i < Integer.MAX_VALUE; i++) { 40 | stack.push(new Object()); 41 | stack.pop(); 42 | } 43 | 44 | for (int i = 0; i < stack.elements.length ; i++) { 45 | System.out.println(" " + stack.elements[i]) ; 46 | } 47 | 48 | System.out.println(" Finished " + stack.elements.length ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/trycatch/Read.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.trycatch; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | public class Read { 8 | 9 | static String firstLineOfFile(String path) throws IOException { 10 | 11 | BufferedReader br = new BufferedReader(new FileReader(path)); 12 | 13 | try { 14 | 15 | return br.readLine(); 16 | 17 | } finally { 18 | 19 | br.close(); 20 | 21 | } 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/trycatch/ReadV2.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.trycatch; 2 | 3 | import java.io.*; 4 | 5 | public class ReadV2 { 6 | 7 | private final static int BUFFER_SIZE = 1000; 8 | 9 | static void copy(String src, String dst) throws IOException { 10 | 11 | InputStream in = new FileInputStream(src); 12 | 13 | try { 14 | 15 | OutputStream out = new FileOutputStream(dst); 16 | 17 | try { 18 | 19 | byte[] buf = new byte[BUFFER_SIZE]; 20 | 21 | int n; 22 | 23 | while ((n = in.read(buf)) >= 0) 24 | 25 | out.write(buf, 0, n); 26 | 27 | } finally { 28 | 29 | out.close(); 30 | 31 | } 32 | 33 | } finally { 34 | 35 | in.close(); 36 | 37 | } 38 | 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/trycatch/ReadV3.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.trycatch; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | public class ReadV3 { 8 | 9 | // try-with-resources - the the best way to close resources! 10 | 11 | // AutoCloseable , Closeable 12 | static String firstLineOfFile(String path) throws IOException { 13 | 14 | try (BufferedReader br = new BufferedReader( 15 | 16 | new FileReader(path))) { 17 | 18 | return br.readLine(); 19 | 20 | } 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/trycatch/ReadV4.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.trycatch; 2 | 3 | import java.io.*; 4 | 5 | public class ReadV4 { 6 | 7 | private final static int BUFFER_SIZE = 1000; 8 | 9 | // try-with-resources on multiple resources - short and sweet 10 | 11 | static void copy(String src, String dst) throws IOException { 12 | 13 | try (InputStream in = new FileInputStream(src); 14 | 15 | OutputStream out = new FileOutputStream(dst)) { 16 | 17 | byte[] buf = new byte[BUFFER_SIZE]; 18 | 19 | int n; 20 | 21 | while ((n = in.read(buf)) >= 0) 22 | 23 | out.write(buf, 0, n); 24 | 25 | } 26 | 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter02/trycatch/ReadV5.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter02.trycatch; 2 | 3 | import java.io.*; 4 | 5 | public class ReadV5 { 6 | 7 | // try-with-resources with a catch clause 8 | 9 | // Ders cok net : Her zaman try - resource kullanalim 10 | 11 | static String firstLineOfFile(String path, String defaultVal) { 12 | 13 | try (BufferedReader br = new BufferedReader( 14 | 15 | new FileReader(path))) { 16 | 17 | return br.readLine(); 18 | 19 | } catch (IOException e) { 20 | 21 | return defaultVal; 22 | 23 | } 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/CaseInsensitiveString.java: -------------------------------------------------------------------------------- 1 | // Broken - violates symmetry! - Pages 36-37 2 | package org.effectivejava.examples.chapter03.item08; 3 | 4 | public final class CaseInsensitiveString { 5 | private final String s; 6 | 7 | public CaseInsensitiveString(String s) { 8 | if (s == null) 9 | throw new NullPointerException(); 10 | this.s = s; 11 | } 12 | 13 | // Broken - violates symmetry! 14 | @Override 15 | public boolean equals(Object o) { 16 | if (o instanceof CaseInsensitiveString) 17 | return s.equalsIgnoreCase(((CaseInsensitiveString) o).s); 18 | if (o instanceof String) // One-way interoperability! 19 | return s.equalsIgnoreCase((String) o); 20 | return false; 21 | } 22 | 23 | // This version is correct. 24 | // @Override public boolean equals(Object o) { 25 | // return o instanceof CaseInsensitiveString && 26 | // ((CaseInsensitiveString) o).s.equalsIgnoreCase(s); 27 | // } 28 | 29 | public static void main(String[] args) { 30 | CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); 31 | String s = "polish"; 32 | System.out.println(cis.equals(s) + " " + s.equals(cis)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/Color.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item08; 2 | 3 | public enum Color { 4 | RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/ColorPoint.java: -------------------------------------------------------------------------------- 1 | // Attempting to add a value component to Point - Pages 37 - 38 2 | package org.effectivejava.examples.chapter03.item08; 3 | 4 | public class ColorPoint extends Point { 5 | private final Color color; 6 | 7 | public ColorPoint(int x, int y, Color color) { 8 | super(x, y); 9 | this.color = color; 10 | } 11 | 12 | // Broken - violates symmetry! 13 | @Override 14 | public boolean equals(Object o) { 15 | if (!(o instanceof ColorPoint)) 16 | return false; 17 | return super.equals(o) && ((ColorPoint) o).color == color; 18 | } 19 | 20 | // Broken - violates transitivity! 21 | // @Override public boolean equals(Object o) { 22 | // if (!(o instanceof Point)) 23 | // return false; 24 | // 25 | // // If o is a normal Point, do a color-blind comparison 26 | // if (!(o instanceof ColorPoint)) 27 | // return o.equals(this); 28 | // 29 | // // o is a ColorPoint; do a full comparison 30 | // return super.equals(o) && ((ColorPoint)o).color == color; 31 | // } 32 | 33 | public static void main(String[] args) { 34 | // First equals function violates symmetry 35 | Point p = new Point(1, 2); 36 | ColorPoint cp = new ColorPoint(1, 2, Color.RED); 37 | System.out.println(p.equals(cp) + " " + cp.equals(p)); 38 | 39 | // Second equals function violates transitivity 40 | ColorPoint p1 = new ColorPoint(1, 2, Color.RED); 41 | Point p2 = new Point(1, 2); 42 | ColorPoint p3 = new ColorPoint(1, 2, Color.BLUE); 43 | System.out.printf("%s %s %s%n", p1.equals(p2), p2.equals(p3), 44 | p1.equals(p3)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/CounterPoint.java: -------------------------------------------------------------------------------- 1 | // Trivial subclass of Point - doesn't add a value component - Page 39 2 | package org.effectivejava.examples.chapter03.item08; 3 | 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class CounterPoint extends Point { 7 | private static final AtomicInteger counter = new AtomicInteger(); 8 | 9 | public CounterPoint(int x, int y) { 10 | super(x, y); 11 | counter.incrementAndGet(); 12 | } 13 | 14 | public int numberCreated() { 15 | return counter.get(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/CounterPointTest.java: -------------------------------------------------------------------------------- 1 | // Test program that uses CounterPoint as Point 2 | package org.effectivejava.examples.chapter03.item08; 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class CounterPointTest { 8 | // Initialize UnitCircle to contain all Points on the unit circle 9 | private static final Set unitCircle; 10 | static { 11 | unitCircle = new HashSet(); 12 | unitCircle.add(new Point(1, 0)); 13 | unitCircle.add(new Point(0, 1)); 14 | unitCircle.add(new Point(-1, 0)); 15 | unitCircle.add(new Point(0, -1)); 16 | } 17 | 18 | public static boolean onUnitCircle(Point p) { 19 | return unitCircle.contains(p); 20 | } 21 | 22 | public static void main(String[] args) { 23 | Point p1 = new Point(1, 0); 24 | Point p2 = new CounterPoint(1, 0); 25 | 26 | // Prints true 27 | System.out.println(onUnitCircle(p1)); 28 | 29 | // Should print true, but doesn't if Point uses getClass-based equals 30 | System.out.println(onUnitCircle(p2)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/Point.java: -------------------------------------------------------------------------------- 1 | // Simple immutable two-dimensional integer point class - Page 37 2 | package org.effectivejava.examples.chapter03.item08; 3 | 4 | public class Point { 5 | private final int x; 6 | private final int y; 7 | 8 | public Point(int x, int y) { 9 | this.x = x; 10 | this.y = y; 11 | } 12 | 13 | @Override 14 | public boolean equals(Object o) { 15 | if (!(o instanceof Point)) 16 | return false; 17 | Point p = (Point) o; 18 | return p.x == x && p.y == y; 19 | } 20 | 21 | // Broken - violates Liskov substitution principle - Pages 39-40 22 | // @Override public boolean equals(Object o) { 23 | // if (o == null || o.getClass() != getClass()) 24 | // return false; 25 | // Point p = (Point) o; 26 | // return p.x == x && p.y == y; 27 | // } 28 | 29 | // See Item 9 30 | @Override 31 | public int hashCode() { 32 | return 31 * x + y; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/composition/Color.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item08.composition; 2 | 3 | public enum Color { 4 | RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/composition/ColorPoint.java: -------------------------------------------------------------------------------- 1 | // Adds a value component without violating the equals contract - Page 40 2 | package org.effectivejava.examples.chapter03.item08.composition; 3 | 4 | public class ColorPoint { 5 | private final Point point; 6 | private final Color color; 7 | 8 | public ColorPoint(int x, int y, Color color) { 9 | if (color == null) 10 | throw new NullPointerException(); 11 | point = new Point(x, y); 12 | this.color = color; 13 | } 14 | 15 | /** 16 | * Returns the point-view of this color point. 17 | */ 18 | public Point asPoint() { 19 | return point; 20 | } 21 | 22 | @Override 23 | public boolean equals(Object o) { 24 | if (!(o instanceof ColorPoint)) 25 | return false; 26 | ColorPoint cp = (ColorPoint) o; 27 | return cp.point.equals(point) && cp.color.equals(color); 28 | } 29 | 30 | @Override 31 | public int hashCode() { 32 | return point.hashCode() * 33 + color.hashCode(); 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item08/composition/Point.java: -------------------------------------------------------------------------------- 1 | // Simple immutable two-dimensional integer point class - Page 37 2 | package org.effectivejava.examples.chapter03.item08.composition; 3 | 4 | public class Point { 5 | private final int x; 6 | private final int y; 7 | 8 | public Point(int x, int y) { 9 | this.x = x; 10 | this.y = y; 11 | } 12 | 13 | @Override 14 | public boolean equals(Object o) { 15 | if (!(o instanceof Point)) 16 | return false; 17 | Point p = (Point) o; 18 | return p.x == x && p.y == y; 19 | } 20 | 21 | // See Item 9 22 | @Override 23 | public int hashCode() { 24 | return 31 * x + y; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item09/kodcu/fixed/TelefonRehberiFixed.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item09.kodcu.fixed; 2 | 3 | // Shows the need for overriding hashcode when you override equals - Pages 45-46 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public final class TelefonRehberiFixed { 9 | private final short alanKod; 10 | private final short prefix; 11 | private final short numara; 12 | 13 | public TelefonRehberiFixed(int alanKod, int prefix, int numara) { 14 | kontrol(alanKod, 999, "alan kod"); 15 | kontrol(prefix, 999, "prefix"); 16 | kontrol(numara, 9999, "numara"); 17 | this.alanKod = (short) alanKod; 18 | this.prefix = (short) prefix; 19 | this.numara = (short) numara; 20 | } 21 | 22 | private static void kontrol(int arg, int max, String name) { 23 | if (arg < 0 || arg > max) 24 | throw new IllegalArgumentException(name + ": " + arg); 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (o == this) 30 | return true; 31 | if (!(o instanceof TelefonRehberiFixed)) 32 | return false; 33 | TelefonRehberiFixed pn = (TelefonRehberiFixed) o; 34 | return pn.numara == numara && pn.prefix == prefix 35 | && pn.alanKod == alanKod; 36 | } 37 | 38 | 39 | @Override 40 | public int hashCode() { 41 | int result = 17; 42 | result = 31 * result + alanKod; 43 | result = 31 * result + prefix; 44 | result = 31 * result + numara; 45 | return result; 46 | } 47 | 48 | 49 | 50 | public static void main(String[] args) { 51 | Map m = new HashMap(); 52 | m.put(new TelefonRehberiFixed(707, 867, 5309), "Ayse"); 53 | System.out.println(m.get(new TelefonRehberiFixed(707, 867, 5309))); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item09/kodcu/questions/TelefonRehberi.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item09.kodcu.questions; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public final class TelefonRehberi { 8 | private final short alanKod; 9 | private final short prefix; 10 | private final short numara; 11 | 12 | public TelefonRehberi(int alanKod, int prefix, int numara) { 13 | numaraKontrol(alanKod, 999, "alan kod"); 14 | numaraKontrol(prefix, 999, "prefix"); 15 | numaraKontrol(numara, 9999, "numara"); 16 | this.alanKod = (short) alanKod; 17 | this.prefix = (short) prefix; 18 | this.numara = (short) numara; 19 | } 20 | 21 | private static void numaraKontrol(int arg, int max, String name) { 22 | if (arg < 0 || arg > max) 23 | throw new IllegalArgumentException(name + ": " + arg); 24 | } 25 | 26 | @Override 27 | public boolean equals(Object o) { 28 | if (o == this) 29 | return true; 30 | if (!(o instanceof TelefonRehberi)) 31 | return false; 32 | TelefonRehberi pn = (TelefonRehberi) o; 33 | return pn.numara == numara && pn.prefix == prefix 34 | && pn.alanKod == alanKod; 35 | } 36 | 37 | 38 | 39 | public static void main(String[] args) { 40 | Map m = new HashMap(); 41 | m.put(new TelefonRehberi(707, 867, 5309), "Ayse"); 42 | System.out.println(m.get(new TelefonRehberi(707, 867, 5309))); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item10/kodcu/fixed/TelefonRehberiFixed.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item10.kodcu.fixed; 2 | 3 | // Shows the need for overriding hashcode when you override equals - Pages 45-46 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public final class TelefonRehberiFixed { 9 | private final short alanKod; 10 | private final short prefix; 11 | private final short numara; 12 | 13 | public TelefonRehberiFixed(int alanKod, int prefix, int numara) { 14 | kontrol(alanKod, 999, "alan kod"); 15 | kontrol(prefix, 999, "prefix"); 16 | kontrol(numara, 9999, "numara"); 17 | this.alanKod = (short) alanKod; 18 | this.prefix = (short) prefix; 19 | this.numara = (short) numara; 20 | } 21 | 22 | private static void kontrol(int arg, int max, String name) { 23 | if (arg < 0 || arg > max) 24 | throw new IllegalArgumentException(name + ": " + arg); 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (o == this) 30 | return true; 31 | if (!(o instanceof TelefonRehberiFixed)) 32 | return false; 33 | TelefonRehberiFixed pn = (TelefonRehberiFixed) o; 34 | return pn.numara == numara && pn.prefix == prefix 35 | && pn.alanKod == alanKod; 36 | } 37 | 38 | 39 | @Override 40 | public int hashCode() { 41 | int result = 17; 42 | result = 31 * result + alanKod; 43 | result = 31 * result + prefix; 44 | result = 31 * result + numara; 45 | return result; 46 | } 47 | 48 | 49 | /** 50 | * Returns the string representation of this phone number. The string 51 | * consists of fourteen characters whose format is "(XXX) YYY-ZZZZ", where 52 | * XXX is the area code, YYY is the prefix, and ZZZZ is the line number. 53 | * (Each of the capital letters represents a single decimal digit.) 54 | * 55 | * If any of the three parts of this phone number is too small to fill up 56 | * its field, the field is padded with leading zeros. For example, if the 57 | * value of the line number is 123, the last four characters of the string 58 | * representation will be "0123". 59 | * 60 | * Note that there is a single space separating the closing parenthesis 61 | * after the area code from the first digit of the prefix. 62 | */ 63 | @Override 64 | public String toString() { 65 | return String.format("(%03d) %03d-%04d", alanKod, prefix, numara); 66 | } 67 | 68 | 69 | public static void main(String[] args) { 70 | Map m = new HashMap(); 71 | m.put(new TelefonRehberiFixed(707, 867, 5309), "Ayse"); 72 | System.out.println(m); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item10/kodcu/questions/TelefonRehberi.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item10.kodcu.questions; 2 | 3 | // Shows the need for overriding hashcode when you override equals - Pages 45-46 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public final class TelefonRehberi { 9 | private final short alanKod; 10 | private final short prefix; 11 | private final short numara; 12 | 13 | public TelefonRehberi(int alanKod, int prefix, int numara) { 14 | kontrol(alanKod, 999, "alan kod"); 15 | kontrol(prefix, 999, "prefix"); 16 | kontrol(numara, 9999, "numara"); 17 | this.alanKod = (short) alanKod; 18 | this.prefix = (short) prefix; 19 | this.numara = (short) numara; 20 | } 21 | 22 | private static void kontrol(int arg, int max, String name) { 23 | if (arg < 0 || arg > max) 24 | throw new IllegalArgumentException(name + ": " + arg); 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (o == this) 30 | return true; 31 | if (!(o instanceof TelefonRehberi)) 32 | return false; 33 | TelefonRehberi pn = (TelefonRehberi) o; 34 | return pn.numara == numara && pn.prefix == prefix 35 | && pn.alanKod == alanKod; 36 | } 37 | 38 | 39 | @Override 40 | public int hashCode() { 41 | int result = 17; 42 | result = 31 * result + alanKod; 43 | result = 31 * result + prefix; 44 | result = 31 * result + numara; 45 | return result; 46 | } 47 | 48 | 49 | 50 | public static void main(String[] args) { 51 | Map m = new HashMap(); 52 | m.put(new TelefonRehberi(707, 867, 5309), "Ayse"); 53 | // print out HashMap content in style 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item11/EmptyStackException.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item11; 2 | 3 | public class EmptyStackException extends IllegalStateException { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item11/PhoneNumber.java: -------------------------------------------------------------------------------- 1 | // Adding a clone method to PhoneNumber - page 55 2 | package org.effectivejava.examples.chapter03.item11; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public final class PhoneNumber implements Cloneable { 8 | private final short areaCode; 9 | private final short prefix; 10 | private final short lineNumber; 11 | 12 | public PhoneNumber(int areaCode, int prefix, int lineNumber) { 13 | rangeCheck(areaCode, 999, "area code"); 14 | rangeCheck(prefix, 999, "prefix"); 15 | rangeCheck(lineNumber, 9999, "line number"); 16 | this.areaCode = (short) areaCode; 17 | this.prefix = (short) prefix; 18 | this.lineNumber = (short) lineNumber; 19 | } 20 | 21 | private static void rangeCheck(int arg, int max, String name) { 22 | if (arg < 0 || arg > max) 23 | throw new IllegalArgumentException(name + ": " + arg); 24 | } 25 | 26 | @Override 27 | public boolean equals(Object o) { 28 | if (o == this) 29 | return true; 30 | if (!(o instanceof PhoneNumber)) 31 | return false; 32 | PhoneNumber pn = (PhoneNumber) o; 33 | return pn.lineNumber == lineNumber && pn.prefix == prefix 34 | && pn.areaCode == areaCode; 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | int result = 17; 40 | result = 31 * result + areaCode; 41 | result = 31 * result + prefix; 42 | result = 31 * result + lineNumber; 43 | return result; 44 | } 45 | 46 | /** 47 | * Returns the string representation of this phone number. The string 48 | * consists of fourteen characters whose format is "(XXX) YYY-ZZZZ", where 49 | * XXX is the area code, YYY is the prefix, and ZZZZ is the line number. 50 | * (Each of the capital letters represents a single decimal digit.) 51 | * 52 | * If any of the three parts of this phone number is too small to fill up 53 | * its field, the field is padded with leading zeros. For example, if the 54 | * value of the line number is 123, the last four characters of the string 55 | * representation will be "0123". 56 | * 57 | * Note that there is a single space separating the closing parenthesis 58 | * after the area code from the first digit of the prefix. 59 | */ 60 | @Override 61 | public String toString() { 62 | return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber); 63 | } 64 | 65 | @Override 66 | public PhoneNumber clone() { 67 | try { 68 | return (PhoneNumber) super.clone(); 69 | } catch (CloneNotSupportedException e) { 70 | throw new AssertionError(); // Can't happen 71 | } 72 | } 73 | 74 | public static void main(String[] args) { 75 | PhoneNumber pn = new PhoneNumber(707, 867, 5309); 76 | Map m = new HashMap(); 77 | m.put(pn, "Jenny"); 78 | System.out.println(m.get(pn.clone())); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item11/Stack.java: -------------------------------------------------------------------------------- 1 | // A cloneable version of Stack - Pages 56-57 2 | package org.effectivejava.examples.chapter03.item11; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Stack implements Cloneable { 7 | private Object[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | public Stack() { 12 | this.elements = new Object[DEFAULT_INITIAL_CAPACITY]; 13 | } 14 | 15 | public void push(Object e) { 16 | ensureCapacity(); 17 | elements[size++] = e; 18 | } 19 | 20 | public Object pop() { 21 | if (size == 0) 22 | throw new EmptyStackException(); 23 | Object result = elements[--size]; 24 | elements[size] = null; // Eliminate obsolete reference 25 | return result; 26 | } 27 | 28 | public boolean isEmpty() { 29 | return size == 0; 30 | } 31 | 32 | @Override 33 | public Stack clone() { 34 | try { 35 | Stack result = (Stack) super.clone(); 36 | result.elements = elements.clone(); 37 | return result; 38 | } catch (CloneNotSupportedException e) { 39 | throw new AssertionError(); 40 | } 41 | } 42 | 43 | // Ensure space for at least one more element. 44 | private void ensureCapacity() { 45 | if (elements.length == size) 46 | elements = Arrays.copyOf(elements, 2 * size + 1); 47 | } 48 | 49 | // To see that clone works, call with several command line arguments 50 | public static void main(String[] args) { 51 | Stack stack = new Stack(); 52 | for (String arg : args) 53 | stack.push(arg); 54 | Stack copy = stack.clone(); 55 | while (!stack.isEmpty()) 56 | System.out.print(stack.pop() + " "); 57 | System.out.println(); 58 | while (!copy.isEmpty()) 59 | System.out.print(copy.pop() + " "); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item12/kodcu/fixed/PhoneNumber.java: -------------------------------------------------------------------------------- 1 | // Making PhoneNumber comparable - Pages 65-66 2 | package org.effectivejava.examples.chapter03.item12.kodcu.fixed; 3 | 4 | import java.util.NavigableSet; 5 | import java.util.Random; 6 | import java.util.TreeSet; 7 | 8 | public final class PhoneNumber implements Cloneable, Comparable { 9 | private final short areaCode; 10 | private final short prefix; 11 | private final short lineNumber; 12 | 13 | public PhoneNumber(int areaCode, int prefix, int lineNumber) { 14 | rangeCheck(areaCode, 999, "area code"); 15 | rangeCheck(prefix, 999, "prefix"); 16 | rangeCheck(lineNumber, 9999, "line number"); 17 | this.areaCode = (short) areaCode; 18 | this.prefix = (short) prefix; 19 | this.lineNumber = (short) lineNumber; 20 | } 21 | 22 | private static void rangeCheck(int arg, int max, String name) { 23 | if (arg < 0 || arg > max) 24 | throw new IllegalArgumentException(name + ": " + arg); 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (o == this) 30 | return true; 31 | if (!(o instanceof PhoneNumber)) 32 | return false; 33 | PhoneNumber pn = (PhoneNumber) o; 34 | return pn.lineNumber == lineNumber && pn.prefix == prefix 35 | && pn.areaCode == areaCode; 36 | } 37 | 38 | @Override 39 | public int hashCode() { 40 | int result = 17; 41 | result = 31 * result + areaCode; 42 | result = 31 * result + prefix; 43 | result = 31 * result + lineNumber; 44 | return result; 45 | } 46 | 47 | /** 48 | * Returns the string representation of this phone number. The string 49 | * consists of fourteen characters whose format is "(XXX) YYY-ZZZZ", where 50 | * XXX is the area code, YYY is the prefix, and ZZZZ is the line number. 51 | * (Each of the capital letters represents a single decimal digit.) 52 | * 53 | * If any of the three parts of this phone number is too small to fill up 54 | * its field, the field is padded with leading zeros. For example, if the 55 | * value of the line number is 123, the last four characters of the string 56 | * representation will be "0123". 57 | * 58 | * Note that there is a single space separating the closing parenthesis 59 | * after the area code from the first digit of the prefix. 60 | */ 61 | @Override 62 | public String toString() { 63 | return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber); 64 | } 65 | 66 | @Override 67 | public PhoneNumber clone() { 68 | try { 69 | return (PhoneNumber) super.clone(); 70 | } catch (CloneNotSupportedException e) { 71 | throw new AssertionError(); // Can't happen 72 | } 73 | } 74 | 75 | // Works fine, but can be made faster 76 | // public int compareTo(PhoneNumber pn) { 77 | // // Compare area codes 78 | // if (areaCode < pn.areaCode) 79 | // return -1; 80 | // if (areaCode > pn.areaCode) 81 | // return 1; 82 | // 83 | // // Area codes are equal, compare prefixes 84 | // if (prefix < pn.prefix) 85 | // return -1; 86 | // if (prefix > pn.prefix) 87 | // return 1; 88 | // 89 | // // Area codes and prefixes are equal, compare line numbers 90 | // if (lineNumber < pn.lineNumber) 91 | // return -1; 92 | // if (lineNumber > pn.lineNumber) 93 | // return 1; 94 | // 95 | // return 0; // All fields are equal 96 | // } 97 | 98 | public int compareTo(PhoneNumber pn) { 99 | // Compare area codes 100 | int areaCodeDiff = areaCode - pn.areaCode; 101 | if (areaCodeDiff != 0) 102 | return areaCodeDiff; 103 | 104 | // Area codes are equal, compare prefixes 105 | int prefixDiff = prefix - pn.prefix; 106 | if (prefixDiff != 0) 107 | return prefixDiff; 108 | 109 | // Area codes and prefixes are equal, compare line numbers 110 | return lineNumber - pn.lineNumber; 111 | } 112 | 113 | public static void main(String[] args) { 114 | NavigableSet s = new TreeSet(); 115 | for (int i = 0; i < 10; i++) 116 | s.add(randomPhoneNumber()); 117 | System.out.println(s); 118 | } 119 | 120 | private static final Random rnd = new Random(); 121 | 122 | private static PhoneNumber randomPhoneNumber() { 123 | return new PhoneNumber((short) rnd.nextInt(1000), 124 | (short) rnd.nextInt(1000), (short) rnd.nextInt(10000)); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item12/kodcu/questions/TelefonNumarasi.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item12.kodcu.questions; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public final class TelefonNumarasi { 8 | private final short alanKod; 9 | private final short prefix; 10 | private final short numara; 11 | 12 | public TelefonNumarasi(int alanKod, int prefix, int numara) { 13 | numaraKontrol(alanKod, 999, "alan kod"); 14 | numaraKontrol(prefix, 999, "prefix"); 15 | numaraKontrol(numara, 9999, "numara"); 16 | this.alanKod = (short) alanKod; 17 | this.prefix = (short) prefix; 18 | this.numara = (short) numara; 19 | } 20 | 21 | private static void numaraKontrol(int arg, int max, String name) { 22 | if (arg < 0 || arg > max) 23 | throw new IllegalArgumentException(name + ": " + arg); 24 | } 25 | 26 | @Override 27 | public boolean equals(Object o) { 28 | if (o == this) 29 | return true; 30 | if (!(o instanceof TelefonNumarasi)) 31 | return false; 32 | TelefonNumarasi pn = (TelefonNumarasi) o; 33 | return pn.numara == numara && pn.prefix == prefix 34 | && pn.alanKod == alanKod; 35 | } 36 | 37 | 38 | 39 | public static void main(String[] args) { 40 | Map m = new HashMap(); 41 | // create random TelefonNumarasi 42 | // sort them accourding to city code 43 | m.put(new TelefonNumarasi(212, 317, 8327), "Ayse Teyze"); 44 | System.out.println(m.get(new TelefonNumarasi(707, 867, 5309))); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter03/item12/kodcu/questions/WordList.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter03.item12.kodcu.questions; 2 | 3 | import java.util.Collections; 4 | import java.util.Set; 5 | import java.util.TreeSet; 6 | 7 | public class WordList { 8 | public static void main(String[] args) { 9 | Set s = new TreeSet(); 10 | Collections.addAll(s, args); 11 | System.out.println(s); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/Item20/kodcu/fixed/Circle.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter04.Item20.kodcu.fixed; 2 | 3 | class Circle extends Figure { 4 | final double radius; 5 | 6 | Circle(double radius) { 7 | this.radius = radius; 8 | } 9 | 10 | double area() { 11 | return Math.PI * (radius * radius); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/Item20/kodcu/fixed/Figure.java: -------------------------------------------------------------------------------- 1 | // Class hierarchy replacement for a tagged class 2 | package org.effectivejava.examples.chapter04.Item20.kodcu.fixed; 3 | 4 | abstract class Figure { 5 | abstract double area(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/Item20/kodcu/fixed/Rectangle.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter04.Item20.kodcu.fixed; 2 | 3 | class Rectangle extends Figure { 4 | final double length; 5 | final double width; 6 | 7 | Rectangle(double length, double width) { 8 | this.length = length; 9 | this.width = width; 10 | } 11 | 12 | double area() { 13 | return length * width; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/Item20/kodcu/fixed/Square.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter04.Item20.kodcu.fixed; 2 | 3 | class Square extends Rectangle { 4 | Square(double side) { 5 | super(side, side); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/Item20/kodcu/questions/Math.java: -------------------------------------------------------------------------------- 1 | // Tagged class - vastly inferior to a class hierarchy! 2 | package org.effectivejava.examples.chapter04.Item20.kodcu.questions; 3 | 4 | class Math { 5 | enum Sekil { 6 | DIKDORTGEN, CEMBER 7 | }; 8 | 9 | // Tag field - the sekil of this figure 10 | final Sekil sekil; 11 | 12 | // These fields are used only if sekil is DIKDORTGEN 13 | double length; 14 | double width; 15 | 16 | // This field is used only if sekil is CEMBER 17 | double radius; 18 | 19 | // Constructor for circle 20 | Math(double radius) { 21 | sekil = Sekil.CEMBER; 22 | this.radius = radius; 23 | } 24 | 25 | // Constructor for rectangle 26 | Math(double length, double width) { 27 | sekil = Sekil.DIKDORTGEN; 28 | this.length = length; 29 | this.width = width; 30 | } 31 | 32 | double area() { 33 | switch (sekil) { 34 | case DIKDORTGEN: 35 | return length * width; 36 | case CEMBER: 37 | return java.lang.Math.PI * (radius * radius); 38 | default: 39 | throw new AssertionError(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item14/Point.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter04.item14; 3 | 4 | class Point { 5 | private final double x; 6 | private final double y; 7 | 8 | public Point(double x, double y) { 9 | this.x = x; 10 | this.y = y; 11 | } 12 | 13 | public double getX() { 14 | return x; 15 | } 16 | 17 | 18 | 19 | public double getY() { 20 | return y; 21 | } 22 | 23 | 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item14/Time.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter04.item14; 3 | 4 | public final class Time { 5 | private static final int HOURS_PER_DAY = 24; 6 | private static final int MINUTES_PER_HOUR = 60; 7 | 8 | //değişmez olması daha az zarar vericidir. 9 | // public erişim belirliyicisine sahip global alanların final ile korunması ?? 10 | public final int hour; 11 | public final int minute; 12 | 13 | 14 | public Time(int hour, int minute) { 15 | if (hour < 0 || hour >= HOURS_PER_DAY) 16 | throw new IllegalArgumentException("Hour: " + hour); 17 | if (minute < 0 || minute >= MINUTES_PER_HOUR) 18 | throw new IllegalArgumentException("Min: " + minute); 19 | this.hour = hour; 20 | this.minute = minute; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item15/Complex.java: -------------------------------------------------------------------------------- 1 | // Immutable class - pages 76-78 2 | package org.effectivejava.examples.chapter04.item15; 3 | 4 | public final class Complex { 5 | private final double re; 6 | private final double im; 7 | 8 | private Complex(double re, double im) { 9 | this.re = re; 10 | this.im = im; 11 | } 12 | 13 | public static Complex valueOf(double re, double im) { 14 | return new Complex(re, im); 15 | } 16 | 17 | public static Complex valueOfPolar(double r, double theta) { 18 | return new Complex(r * Math.cos(theta), r * Math.sin(theta)); 19 | } 20 | 21 | public static final Complex ZERO = new Complex(0, 0); 22 | public static final Complex ONE = new Complex(1, 0); 23 | public static final Complex I = new Complex(0, 1); 24 | 25 | // Accessors with no corresponding mutators 26 | public double realPart() { 27 | return re; 28 | } 29 | 30 | public double imaginaryPart() { 31 | return im; 32 | } 33 | 34 | public Complex add(Complex c) { 35 | return new Complex(re + c.re, im + c.im); 36 | } 37 | 38 | public Complex subtract(Complex c) { 39 | return new Complex(re - c.re, im - c.im); 40 | } 41 | 42 | public Complex multiply(Complex c) { 43 | return new Complex(re * c.re - im * c.im, re * c.im + im * c.re); 44 | } 45 | 46 | public Complex divide(Complex c) { 47 | double tmp = c.re * c.re + c.im * c.im; 48 | return new Complex((re * c.re + im * c.im) / tmp, (im * c.re - re 49 | * c.im) 50 | / tmp); 51 | } 52 | 53 | @Override 54 | public boolean equals(Object o) { 55 | if (o == this) 56 | return true; 57 | if (!(o instanceof Complex)) 58 | return false; 59 | Complex c = (Complex) o; 60 | 61 | // See page 43 to find out why we use compare instead of == 62 | return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0; 63 | } 64 | 65 | @Override 66 | public int hashCode() { 67 | int result = 17 + hashDouble(re); 68 | result = 31 * result + hashDouble(im); 69 | return result; 70 | } 71 | 72 | private int hashDouble(double val) { 73 | long longBits = Double.doubleToLongBits(re); 74 | return (int) (longBits ^ (longBits >>> 32)); 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "(" + re + " + " + im + "i)"; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item16/kodcu/questions/MyHashSet.java: -------------------------------------------------------------------------------- 1 | // Broken - Inappropriate use of inheritance! 2 | package org.effectivejava.examples.chapter04.item16.kodcu.questions; 3 | 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | import java.util.HashSet; 7 | 8 | public class MyHashSet extends HashSet { 9 | // The number of attempted element insertions 10 | private int addCount = 0; 11 | 12 | public MyHashSet() { 13 | } 14 | 15 | public MyHashSet(int initCap, float loadFactor) { 16 | super(initCap, loadFactor); 17 | } 18 | 19 | @Override 20 | public boolean add(E e) { 21 | addCount++; 22 | return super.add(e); 23 | } 24 | 25 | @Override 26 | public boolean addAll(Collection c) { 27 | addCount += c.size(); 28 | return super.addAll(c); 29 | } 30 | 31 | public int getAddCount() { 32 | return addCount; 33 | } 34 | 35 | public static void main(String[] args) { 36 | MyHashSet s = new MyHashSet(); 37 | s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); 38 | System.out.println(s.getAddCount()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item17/kodcu/questions/Ast.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter04.item17.kodcu.questions; 2 | 3 | import java.util.Date; 4 | 5 | public final class Ast extends Super { 6 | private final Date date; // Blank final, set by constructor 7 | 8 | Ast() { 9 | date = new Date(); 10 | } 11 | 12 | // Overriding method invoked by superclass constructor 13 | @Override 14 | public void overrideMe() { 15 | System.out.println(date); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Ast ast = new Ast(); 20 | ast.overrideMe(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item17/kodcu/questions/Super.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter04.item17.kodcu.questions; 2 | 3 | public class Super { 4 | // Broken - constructor invokes an overridable method 5 | public Super() { 6 | overrideMe(); 7 | } 8 | 9 | public void overrideMe() { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item18/AbstractMapEntry.java: -------------------------------------------------------------------------------- 1 | // Skeletal Implementation - Page 96 2 | package org.effectivejava.examples.chapter04.item18; 3 | 4 | import java.util.Map; 5 | 6 | public abstract class AbstractMapEntry implements Map.Entry { 7 | // Primitive operations 8 | public abstract K getKey(); 9 | 10 | public abstract V getValue(); 11 | 12 | // Entries in modifiable maps must override this method 13 | public V setValue(V value) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | // Implements the general contract of Map.Entry.equals 18 | @Override 19 | public boolean equals(Object o) { 20 | if (o == this) 21 | return true; 22 | if (!(o instanceof Map.Entry)) 23 | return false; 24 | Map.Entry arg = (Map.Entry) o; 25 | return equals(getKey(), arg.getKey()) 26 | && equals(getValue(), arg.getValue()); 27 | } 28 | 29 | private static boolean equals(Object o1, Object o2) { 30 | return o1 == null ? o2 == null : o1.equals(o2); 31 | } 32 | 33 | // Implements the general contract of Map.Entry.hashCode 34 | @Override 35 | public int hashCode() { 36 | return hashCode(getKey()) ^ hashCode(getValue()); 37 | } 38 | 39 | private static int hashCode(Object obj) { 40 | return obj == null ? 0 : obj.hashCode(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item18/IntArrays.java: -------------------------------------------------------------------------------- 1 | // Concrete implementation built atop skeletal implementation - Page 95 2 | package org.effectivejava.examples.chapter04.item18; 3 | 4 | import java.util.AbstractList; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | public class IntArrays { 9 | static List intArrayAsList(final int[] a) { 10 | if (a == null) 11 | throw new NullPointerException(); 12 | 13 | return new AbstractList() { 14 | public Integer get(int i) { 15 | return a[i]; // Autoboxing (Item 5) 16 | } 17 | 18 | @Override 19 | public Integer set(int i, Integer val) { 20 | int oldVal = a[i]; 21 | a[i] = val; // Auto-unboxing 22 | return oldVal; // Autoboxing 23 | } 24 | 25 | public int size() { 26 | return a.length; 27 | } 28 | }; 29 | } 30 | 31 | public static void main(String[] args) { 32 | int[] a = new int[10]; 33 | for (int i = 0; i < a.length; i++) 34 | a[i] = i; 35 | List list = intArrayAsList(a); 36 | 37 | Collections.shuffle(list); 38 | System.out.println(list); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item19/kodcu/fixed/PhysicalConstants.java: -------------------------------------------------------------------------------- 1 | // Constant utility class 2 | package org.effectivejava.examples.chapter04.item19.kodcu.fixed; 3 | 4 | public class PhysicalConstants { 5 | private PhysicalConstants() { 6 | } // Prevents instantiation 7 | 8 | // Avogadro's number (1/mol) 9 | public static final double AVOGADROS_NUMBER = 6.02214199e23; 10 | 11 | // Boltzmann constant (J/K) 12 | public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; 13 | 14 | // Mass of the electron (kg) 15 | public static final double ELECTRON_MASS = 9.10938188e-31; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter04/item19/kodcu/questions/IPhysicalConstants.java: -------------------------------------------------------------------------------- 1 | // Constant utility class 2 | package org.effectivejava.examples.chapter04.item19.kodcu.questions; 3 | 4 | public interface IPhysicalConstants { 5 | 6 | // Avogadro's number (1/mol) 7 | static final double AVOGADROS_NUMBER = 6.02214199e23; 8 | 9 | // Boltzmann constant (J/K) 10 | static final double BOLTZMANN_CONSTANT = 1.3806503e-23; 11 | 12 | // Mass of the electron (kg) 13 | static final double ELECTRON_MASS = 9.10938188e-31; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item23/kodcu/fixed/Raw.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item23.kodcu.fixed; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | public class Raw { 9 | 10 | public static void main(String[] args) { 11 | Set strings = new HashSet(); 12 | strings.add(new String("adad")); 13 | 14 | Set integers = new HashSet(); 15 | integers.add(new Integer(5)); 16 | 17 | numElementsInCommon(strings, integers); 18 | 19 | } 20 | 21 | private static void unsafeAdd(List list, Object o) { 22 | list.add(o); 23 | } 24 | 25 | 26 | static int rawNumElementsInCommon(Set s1, Set s2) { 27 | int result = 0; 28 | for (Object o1 : s1) 29 | if (s2.contains(o1)) 30 | result++; 31 | return result; 32 | } 33 | 34 | 35 | static int numElementsInCommon(Set s1, Set s2) { 36 | //s1.add("selam"); 37 | int result = 0; 38 | for (Object o1 : s1) 39 | if (s2.contains(o1)) 40 | result++; 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item23/kodcu/fixed/TypeShowCase.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item23.kodcu.fixed; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /* 8 | class Arac extends Object{} 9 | class Araba extends Arac {} 10 | class SporAraba extends Araba {} 11 | class AileArabasi extends Araba {} 12 | 13 | 14 | public class TypeShowCase { 15 | 16 | List aracListesi; 17 | List arabaListesi; 18 | 19 | { 20 | 21 | aracListesi = new ArrayList(); // ?? 22 | aracListesi = new ArrayList(); // ?? 23 | aracListesi = new ArrayList(); // ?? 24 | 25 | 26 | arabaListesi = new ArrayList(); // ?? 27 | arabaListesi = new ArrayList(); // ?? 28 | 29 | //someMethod(aracListesi); 30 | 31 | 32 | } 33 | 34 | public void someMethod(List lb) { 35 | Araba araba = lb.get(0); // ?? 36 | lb.add(new Araba()); // ?? 37 | } 38 | 39 | public void otherMethod(List lb) { 40 | Araba araba = lb.get(0); // ?? 41 | lb.add(new Araba()); // ?? 42 | } 43 | 44 | } 45 | */ 46 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item23/kodcu/questions/KahveDukkani.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item23.kodcu.questions; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | public class KahveDukkani { 8 | // Uses raw type (List) - fails at runtime! 9 | public static void main(String[] args) { 10 | List strings = new ArrayList(); 11 | tehlikeliEkleme(strings, new Integer(42)); 12 | String s = strings.get(0); // cast by Compiler 13 | } 14 | 15 | private static void tehlikeliEkleme(List list, Object o) { 16 | list.add(o); 17 | } 18 | 19 | // Belirsiz tip cevrimi - tehlikeli - yapmayin 20 | static int say(Set s1, Set s2) { 21 | int result = 0; 22 | for (Object o1 : s1) 23 | if (s2.contains(o1)) 24 | result++; 25 | return result; 26 | } 27 | 28 | // Unbounded wildcard type - tip güvenligi var ve esnek 29 | static int sayWildcard(Set s1, Set s2) { 30 | int result = 0; 31 | for (Object o1 : s1) 32 | if (s2.contains(o1)) 33 | result++; 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item25/kodcu/questions/Function.java: -------------------------------------------------------------------------------- 1 | // Generic Function interface - Page 122 2 | package org.effectivejava.examples.chapter05.item25.kodcu.questions; 3 | 4 | interface Function { 5 | T apply(T arg1, T arg2); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item25/kodcu/questions/Main.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item25.kodcu.questions; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Main { 8 | 9 | public static void main(String[] args) { 10 | 11 | //Object[] objectArray = new Long[1]; 12 | //objectArray[0] = "Selam"; 13 | 14 | //List objectList = new ArrayList(); 15 | //objectList.add("selam"); 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item25/kodcu/questions/Reduction.java: -------------------------------------------------------------------------------- 1 | // List-based generic reduction - Page 123 2 | package org.effectivejava.examples.chapter05.item25.kodcu.questions; 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | public class Reduction { 9 | static E reduce(List list, Function f, E initVal) { 10 | List snapshot; 11 | synchronized (list) { // onemli 12 | snapshot = new ArrayList(list); 13 | } 14 | E result = initVal; 15 | for (E e : snapshot) 16 | result = f.apply(result, e); 17 | return result; 18 | } 19 | 20 | // A few sample functions 21 | 22 | private static final Function SUM = new Function() { 23 | public Integer apply(Integer i1, Integer i2) { 24 | return i1 + i2; 25 | } 26 | }; 27 | 28 | private static final Function PRODUCT = new Function() { 29 | public Integer apply(Integer i1, Integer i2) { 30 | return i1 * i2; 31 | } 32 | }; 33 | 34 | private static final Function MAX = new Function() { 35 | public Integer apply(Integer i1, Integer i2) { 36 | return Math.max(i1, i2); 37 | } 38 | }; 39 | 40 | private static final Function MIN = new Function() { 41 | public Integer apply(Integer i1, Integer i2) { 42 | return Math.min(i1, i2); 43 | } 44 | }; 45 | 46 | public static void main(String[] args) { 47 | List intList = Arrays.asList(2, 7, 1, 8, 2, 8, 1, 8, 2, 8); 48 | 49 | // Reduce intList using each of the above reducers 50 | System.out.println(reduce(intList, SUM, 0)); 51 | System.out.println(reduce(intList, PRODUCT, 1)); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item26/kodcu/fixed/firsttechnqiue/EmptyStackException.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item26.kodcu.fixed.firsttechnqiue; 2 | 3 | public class EmptyStackException extends RuntimeException { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item26/kodcu/fixed/firsttechnqiue/Stack.java: -------------------------------------------------------------------------------- 1 | // Generic stack using E[] - Pages 125-127 2 | package org.effectivejava.examples.chapter05.item26.kodcu.fixed.firsttechnqiue; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Stack { 7 | private E[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | // The elements array will contain only E instances from push(E). 12 | // This is sufficient to ensure type safety, but the runtime 13 | // type of the array won't be E[]; it will always be Object[]! 14 | @SuppressWarnings("unchecked") 15 | public Stack() { 16 | elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY]; 17 | } 18 | 19 | public void push(E e) { 20 | ensureCapacity(); 21 | elements[size++] = e; 22 | } 23 | 24 | public E pop() { 25 | if (size == 0) 26 | throw new EmptyStackException(); 27 | E result = elements[--size]; 28 | elements[size] = null; // Eliminate obsolete reference 29 | return result; 30 | } 31 | 32 | public boolean isEmpty() { 33 | return size == 0; 34 | } 35 | 36 | private void ensureCapacity() { 37 | if (elements.length == size) 38 | elements = Arrays.copyOf(elements, 2 * size + 1); 39 | } 40 | 41 | // Little program to exercise our generic Stack 42 | public static void main(String[] args) { 43 | Stack stack = new Stack(); 44 | for (String arg : args) 45 | stack.push(arg); 46 | while (!stack.isEmpty()) 47 | System.out.println(stack.pop().toUpperCase()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item26/kodcu/fixed/secondtechnqiue/EmptyStackException.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item26.kodcu.fixed.secondtechnqiue; 2 | 3 | public class EmptyStackException extends RuntimeException { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item26/kodcu/fixed/secondtechnqiue/Stack.java: -------------------------------------------------------------------------------- 1 | // Generic stack using Object[] - Pages 125-127 2 | package org.effectivejava.examples.chapter05.item26.kodcu.fixed.secondtechnqiue; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Stack { 7 | private Object[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | public Stack() { 12 | elements = new Object[DEFAULT_INITIAL_CAPACITY]; 13 | } 14 | 15 | public void push(E e) { 16 | ensureCapacity(); 17 | elements[size++] = e; 18 | } 19 | 20 | // Appropriate suppression of unchecked warning 21 | public E pop() { 22 | if (size == 0) 23 | throw new EmptyStackException(); 24 | 25 | // push requires elements to be of type E, so cast is correct 26 | @SuppressWarnings("unchecked") 27 | E result = (E) elements[--size]; 28 | 29 | elements[size] = null; // Eliminate obsolete reference 30 | return result; 31 | } 32 | 33 | public boolean isEmpty() { 34 | return size == 0; 35 | } 36 | 37 | private void ensureCapacity() { 38 | if (elements.length == size) 39 | elements = Arrays.copyOf(elements, 2 * size + 1); 40 | } 41 | 42 | // Little program to exercise our generic Stack 43 | public static void main(String[] args) { 44 | Stack stack = new Stack(); 45 | for (String arg : args) 46 | stack.push(arg); 47 | while (!stack.isEmpty()) 48 | System.out.println(stack.pop().toUpperCase()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item26/kodcu/questions/Stack.java: -------------------------------------------------------------------------------- 1 | package org.effectivejava.examples.chapter05.item26.kodcu.questions; 2 | 3 | import java.util.Arrays; 4 | 5 | // Object-based collection - a prime candidate for generics 6 | public class Stack { 7 | private Object[] elements; 8 | private int size = 0; 9 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 10 | 11 | public Stack() { 12 | elements = new Object[DEFAULT_INITIAL_CAPACITY]; 13 | } 14 | 15 | public void push(Object e) { 16 | ensureCapacity(); 17 | elements[size++] = e; 18 | } 19 | 20 | public Object pop() { 21 | if (size == 0) 22 | throw new RuntimeException(); 23 | Object result = elements[--size]; 24 | elements[size] = null; // Eliminate obsolete reference 25 | return result; 26 | } 27 | 28 | public boolean isEmpty() { 29 | return size == 0; 30 | } 31 | 32 | private void ensureCapacity() { 33 | if (elements.length == size) 34 | elements = Arrays.copyOf(elements, 2 * size + 1); 35 | } 36 | 37 | public static void main(String[] args) { 38 | Stack stack = new Stack(); 39 | for (String arg : args) { 40 | stack.push(arg); 41 | // Gelen String neslerini buyuk harfe cevirelim (uppercase) 42 | Object ob = stack.pop(); 43 | String pop = (String) ob; 44 | System.out.println(pop.toUpperCase()); 45 | } 46 | 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item27/kodcu/fixed/Union.java: -------------------------------------------------------------------------------- 1 | // Generic union method and program to exercise it - pages 129 - 130 2 | package org.effectivejava.examples.chapter05.item27.kodcu.fixed; 3 | 4 | import java.util.Arrays; 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | public class Union { 9 | 10 | // Generic method 11 | public static Set union(Set s1, Set s2) { 12 | Set result = new HashSet(s1); 13 | result.addAll(s2); 14 | return result; 15 | } 16 | 17 | // Simple program to exercise generic method 18 | public static void main(String[] args) { 19 | Set guys = new HashSet(Arrays.asList("Tom", "Heid", 20 | "Harry")); 21 | Set stooges = new HashSet(Arrays.asList("Sonmez", "Ates", 22 | "Curly")); 23 | 24 | /* 25 | Set ints = new HashSet(Arrays.asList(12, 13, 14)); 26 | Set go = union(guys, ints); 27 | for (Integer intValue : go) { 28 | System.out.println(intValue); 29 | } 30 | */ 31 | 32 | Set aflCio = union(guys, stooges); 33 | System.out.println(aflCio); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item27/kodcu/questions/KelimeBirlestirmece.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter05.item27.kodcu.questions; 3 | 4 | import java.util.Arrays; 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | public class KelimeBirlestirmece { 9 | 10 | 11 | public static Set birlestir(Set s1, Set s2) { 12 | Set result = new HashSet(s1); 13 | result.addAll(s2); 14 | return result; 15 | 16 | } 17 | 18 | 19 | public static void main(String[] args) { 20 | Set marmaraBolgesiSehirleri = new HashSet(Arrays.asList("Edirne", "Edirne", "Tekirdag", "Kocaeli")); 21 | Set egeBolgesiSehirleri = new HashSet(Arrays.asList("Izmir", "Aydin", "Mugla")); 22 | 23 | Set aflCio = birlestir(marmaraBolgesiSehirleri, egeBolgesiSehirleri); 24 | System.out.println(aflCio); 25 | 26 | // TODO 27 | 28 | /* 29 | Set ints = new HashSet(Arrays.asList(12, 13, 14)); 30 | Set go = birlestir(marmaraBolgesiSehirleri, egeBolgesiSehirleri); 31 | for (Integer intValue : go) { 32 | System.out.println(intValue); 33 | } 34 | 35 | */ 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item28/kodcu/fixed/ParkInnFixed.java: -------------------------------------------------------------------------------- 1 | // Generic union method with wildcard types - Pages 137-138 2 | package org.effectivejava.examples.chapter05.item28.kodcu.fixed; 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class ParkInnFixed { 8 | 9 | public static Set birlestir(Set s1, Set s2) { 10 | Set result = new HashSet(s1); 11 | result.addAll(s2); 12 | return result; 13 | } 14 | 15 | // Simple program to exercise flexible generic method 16 | public static void main(String[] args) { 17 | Set integers = new HashSet(); 18 | integers.add(1); 19 | integers.add(3); 20 | integers.add(5); 21 | 22 | Set doubles = new HashSet(); 23 | doubles.add(2.0); 24 | doubles.add(4.0); 25 | doubles.add(6.0); 26 | 27 | 28 | Set numbers = ParkInnFixed.birlestir(integers, doubles); 29 | 30 | System.out.println(numbers); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter05/item28/kodcu/questions/ParkInn.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter05.item28.kodcu.questions; 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class ParkInn { 8 | 9 | public static Set birlestir(Set s1, Set s2) { 10 | Set result = new HashSet(s1); 11 | result.addAll(s2); 12 | return result; 13 | } 14 | 15 | // Simple program to exercise flexible generic method 16 | public static void main(String[] args) { 17 | Set integers = new HashSet(); 18 | integers.add(1); 19 | integers.add(3); 20 | integers.add(5); 21 | 22 | Set doubles = new HashSet(); 23 | doubles.add(2.0); 24 | doubles.add(4.0); 25 | doubles.add(6.0); 26 | 27 | // TODO yorum satirlarini aciniz 28 | //Set numbers = ParkInn.birlestir(integers, doubles); 29 | // System.out.println(numbers); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter06/item30/kodcu/fixed/Planet.java: -------------------------------------------------------------------------------- 1 | // Enum type with data and behavior - Pages 149-150 2 | package org.effectivejava.examples.chapter06.item30.kodcu.fixed; 3 | 4 | public enum Planet { 5 | MERCURY(3.302e+23, 2.439e6), VENUS(4.869e+24, 6.052e6), EARTH(5.975e+24, 6 | 6.378e6), MARS(6.419e+23, 3.393e6), JUPITER(1.899e+27, 7.149e7), SATURN( 7 | 5.685e+26, 6.027e7), URANUS(8.683e+25, 2.556e7), NEPTUNE(1.024e+26, 8 | 2.477e7); 9 | private final double mass; // In kilograms 10 | private final double radius; // In meters 11 | private final double surfaceGravity; // In m / s^2 12 | 13 | // Universal gravitational constant in m^3 / kg s^2 14 | private static final double G = 6.67300E-11; 15 | 16 | // Constructor 17 | Planet(double mass, double radius) { 18 | this.mass = mass; 19 | this.radius = radius; 20 | surfaceGravity = G * mass / (radius * radius); 21 | } 22 | 23 | public double mass() { 24 | return mass; 25 | } 26 | 27 | public double radius() { 28 | return radius; 29 | } 30 | 31 | public double surfaceGravity() { 32 | return surfaceGravity; 33 | } 34 | 35 | public double surfaceWeight(double mass) { 36 | return mass * surfaceGravity; // F = ma 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter06/item30/kodcu/fixed/WeightTable.java: -------------------------------------------------------------------------------- 1 | // Takes earth-weight and prints table of weights on all planets - Page 150 2 | package org.effectivejava.examples.chapter06.item30.kodcu.fixed; 3 | 4 | 5 | public class WeightTable { 6 | public static void main(String[] args) { 7 | double earthWeight = Double.parseDouble("10"); 8 | double mass = earthWeight / Planet.EARTH.surfaceGravity(); 9 | for (Planet p : Planet.values()) 10 | System.out.printf("Weight on %s is %f%n", p, p.surfaceWeight(mass)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter06/item30/kodcu/questions/Bordro.java: -------------------------------------------------------------------------------- 1 | 2 | package org.effectivejava.examples.chapter06.item30.kodcu.questions; 3 | 4 | enum Bordro { 5 | 6 | PAZARTESI(OdemeTipi.HAFTA_ICI), SALI(OdemeTipi.HAFTA_ICI), CARSAMBA( 7 | OdemeTipi.HAFTA_ICI), PERSEMBE(OdemeTipi.HAFTA_ICI), CUMA(OdemeTipi.HAFTA_ICI), CUMARTESI( 8 | OdemeTipi.HAFTA_SONU), PAZAR(OdemeTipi.HAFTA_SONU); 9 | 10 | private final OdemeTipi odemeTipi; 11 | 12 | Bordro(OdemeTipi odemeTipi) { 13 | this.odemeTipi = odemeTipi; 14 | } 15 | 16 | double tutarHesapla(double calistigiSaat, double oran) { 17 | return odemeTipi.odemeYap(calistigiSaat, oran); 18 | } 19 | 20 | // The strategy enum type 21 | private enum OdemeTipi { 22 | HAFTA_ICI { 23 | double tutarHesapla(double saat, double oran) { 24 | return saat * oran * 2; 25 | } 26 | }, 27 | HAFTA_SONU { 28 | double tutarHesapla(double saat, double oran) { 29 | return saat * oran / 2; 30 | } 31 | }; 32 | 33 | 34 | abstract double tutarHesapla(double saat, double oran); 35 | 36 | double odemeYap(double calistigiSaat, double oran) { 37 | double bazTutar = calistigiSaat * oran; 38 | return bazTutar + tutarHesapla(calistigiSaat, oran); 39 | } 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter06/item31/Ensemble.java: -------------------------------------------------------------------------------- 1 | // Enum with integer data stored in an instance field 2 | package org.effectivejava.examples.chapter06.item31; 3 | 4 | public enum Ensemble { 5 | SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5), SEXTET(6), SEPTET(7), OCTET( 6 | 8), DOUBLE_QUARTET(8), NONET(9), DECTET(10), TRIPLE_QUARTET(12); 7 | 8 | private final int numberOfMusicians; 9 | 10 | Ensemble(int size) { 11 | this.numberOfMusicians = size; 12 | } 13 | 14 | public int numberOfMusicians() { 15 | return numberOfMusicians; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/effectivejava/examples/chapter06/item32/kodcu/fixed/Text.java: -------------------------------------------------------------------------------- 1 | // EnumSet - a modern replacement for bit fields - Page 160 2 | package org.effectivejava.examples.chapter06.item32.kodcu.fixed; 3 | 4 | import java.util.EnumSet; 5 | import java.util.Set; 6 | 7 | public class Text { 8 | public enum Style { 9 | BOLD, ITALIC, UNDERLINE, STRIKETHROUGH 10 | } 11 | 12 | // Any Set could be passed in, but EnumSet is clearly best 13 | public void applyStyles(Set