├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── java │ └── net │ │ └── harunote │ │ ├── pattern │ │ ├── factory │ │ │ ├── car │ │ │ │ ├── CarType.java │ │ │ │ ├── SedanCar.java │ │ │ │ ├── LuxuryCar.java │ │ │ │ ├── SmallCar.java │ │ │ │ ├── TestFactoryPattern.java │ │ │ │ ├── CarFactory.java │ │ │ │ └── Car.java │ │ │ ├── pizzastore │ │ │ │ ├── NyStyleClamPizza.java │ │ │ │ ├── NyStyleVeggiePizza.java │ │ │ │ ├── ChicagoStyleClamPizza.java │ │ │ │ ├── NyStylePepperoniPizza.java │ │ │ │ ├── ChicagoStyleVeggiePizza.java │ │ │ │ ├── ChicagoStylePepperoniPizza.java │ │ │ │ ├── NyStyleCheesePizza.java │ │ │ │ ├── PizzaStore.java │ │ │ │ ├── ChicagoStyleCheesePizza.java │ │ │ │ ├── ChicagoStylePizza.java │ │ │ │ ├── PizzaStoreTestDrive.java │ │ │ │ ├── NyPizzaStore.java │ │ │ │ ├── ChicagoPizzaStore.java │ │ │ │ └── Pizza.java │ │ │ ├── package-info.java │ │ │ └── legacy │ │ │ │ ├── Car.java │ │ │ │ └── CarTest.java │ │ ├── command │ │ │ ├── logging │ │ │ │ ├── Command.java │ │ │ │ ├── Invoker.java │ │ │ │ ├── Logger.java │ │ │ │ ├── LoggerApp.java │ │ │ │ └── LogCommand.java │ │ │ ├── Command.java │ │ │ ├── SellStock.java │ │ │ ├── BuyStock.java │ │ │ ├── Stock.java │ │ │ ├── Broker.java │ │ │ └── CommandPatternApp.java │ │ ├── adapter │ │ │ ├── package-info.java │ │ │ ├── MediaPlayer.java │ │ │ ├── AdvancedMediaPlayer.java │ │ │ ├── Mp4Player.java │ │ │ ├── VlcPlayer.java │ │ │ ├── AdapterPatternApp.java │ │ │ ├── AudioPlayer.java │ │ │ └── MediaAdapter.java │ │ ├── strategy │ │ │ ├── CalculationStrategy.java │ │ │ ├── AddOperation.java │ │ │ ├── DivideOperation.java │ │ │ ├── MultiplyOperation.java │ │ │ ├── SubstractOperation.java │ │ │ ├── Calculation.java │ │ │ ├── Calculator.java │ │ │ └── CalculationDemo.java │ │ ├── decorator │ │ │ ├── CondimentDecorator.java │ │ │ ├── DarkRoast.java │ │ │ ├── Beverage.java │ │ │ ├── Decaf.java │ │ │ ├── Espresso.java │ │ │ ├── HouseBlend.java │ │ │ ├── Soy.java │ │ │ ├── Mocha.java │ │ │ ├── Whip.java │ │ │ └── StarBuzzApps.java │ │ ├── singleton │ │ │ ├── package-info.java │ │ │ ├── Singleton.java │ │ │ ├── EagerSingleton.java │ │ │ ├── LazySingleton.java │ │ │ ├── InitializationOnDemandHolderIdiom.java │ │ │ └── LazySingletonDoubleCheckLocking.java │ │ ├── facade │ │ │ ├── FacedeApp.java │ │ │ ├── MySqlHelper.java │ │ │ ├── WithoutFacadeInterfaceApp.java │ │ │ ├── OracleHelper.java │ │ │ └── HelperFacade.java │ │ └── template │ │ │ ├── application │ │ │ ├── GlassHouse.java │ │ │ ├── WoodenHouse.java │ │ │ └── HouseTemplate.java │ │ │ └── HousingApp.java │ │ ├── java8 │ │ ├── functional │ │ │ ├── consumer │ │ │ │ ├── PrintLength.java │ │ │ │ ├── PrintLengthApp.java │ │ │ │ └── ConsumerExample.java │ │ │ ├── predicate │ │ │ │ ├── Tshirt.java │ │ │ │ ├── TshirtPredicate.java │ │ │ │ └── TshirtPredicateApp.java │ │ │ ├── function │ │ │ │ └── StringLengthExample.java │ │ │ └── supplier │ │ │ │ └── RandomNumberSupplier.java │ │ ├── lambda │ │ │ ├── runnable │ │ │ │ ├── RunnableThread.java │ │ │ │ ├── RunnableInterfaceApp.java │ │ │ │ └── RunnableLambda.java │ │ │ └── comparator │ │ │ │ ├── TshirtSorterLambda.java │ │ │ │ └── TshirtSorter.java │ │ └── parameterization │ │ │ ├── ExecutionExampleApp.java │ │ │ ├── SortingExampleApp.java │ │ │ ├── MappingExampleApp.java │ │ │ ├── EvenNumberPredicate.java │ │ │ ├── FilteringExampleApp.java │ │ │ └── CombinationExample.java │ │ ├── quiz │ │ ├── input │ │ │ ├── TextInput.java │ │ │ ├── NumericInput.java │ │ │ └── UserInput.java │ │ ├── ReverseString.java │ │ ├── ReverseString2.java │ │ ├── StrToInt.java │ │ ├── arrays │ │ │ ├── ArraySort.java │ │ │ ├── ArrayIndexPosition.java │ │ │ ├── MultiDimensional.java │ │ │ └── LeftLotation.java │ │ ├── practice │ │ │ ├── EqualString.java │ │ │ ├── LibraryFine.java │ │ │ ├── CurrentBuffer.java │ │ │ ├── CheckBinarySearchTree.java │ │ │ ├── CompareTheTriplets.java │ │ │ ├── MakingAnagrams.java │ │ │ └── HashtableRansomNote.java │ │ ├── PrintTriangle.java │ │ ├── EvenOrOdd.java │ │ ├── BinaryGap.java │ │ ├── FindKim.java │ │ ├── WaterMelon.java │ │ ├── calculation │ │ │ └── Average.java │ │ ├── EncodedString.java │ │ ├── TimeConversion.java │ │ ├── BirthdayCakeCandle.java │ │ ├── Palindrom.java │ │ ├── MinimumMoves.java │ │ ├── TimeDiffCalculator.java │ │ ├── PlusMinusGroup.java │ │ ├── BinaryCadinality.java │ │ └── Bracket.java │ │ ├── collection │ │ ├── sort │ │ │ ├── actor │ │ │ │ ├── PrizeYearComparator.java │ │ │ │ ├── Actor.java │ │ │ │ └── FilmFestival.java │ │ │ ├── Product.java │ │ │ ├── ListSort.java │ │ │ ├── ArraySort.java │ │ │ ├── TestMap.java │ │ │ └── ComplexSort.java │ │ ├── TreeSetDemo.java │ │ ├── LinkedHashSetDemo.java │ │ ├── HashSetDemo.java │ │ ├── ArrayListToArrayDemo.java │ │ ├── ArrayListDemo.java │ │ ├── HashTableDemo.java │ │ ├── MapDemo.java │ │ ├── LinkedListDemo.java │ │ ├── structure │ │ │ ├── PriorityQueueExample.java │ │ │ ├── StackExample.java │ │ │ ├── QueueExample.java │ │ │ └── DequeExample.java │ │ ├── HashMapDemo.java │ │ ├── TreeMapDemo.java │ │ └── AlgorithmsDemo.java │ │ └── algorithm │ │ ├── sort │ │ ├── ListSort.java │ │ ├── ArraySort.java │ │ ├── InsertionSort.java │ │ ├── BubbleSort.java │ │ ├── SelectionSort.java │ │ ├── QuickSort.java │ │ └── MergeSort.java │ │ ├── loadbalancer │ │ ├── RoundRobinLoadBalancer.java │ │ └── LeastConnectionsLoadBalancer.java │ │ ├── lru │ │ └── LRUCache.java │ │ ├── complexity │ │ └── ComplexityTest.java │ │ └── lfu │ │ └── LFUCache.java │ └── resources │ └── log4j.properties ├── .idea └── vcs.xml ├── .gitignore ├── gradlew.bat ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'tech-interview' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/villainscode/tech-interview/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/CarType.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | public enum CarType { 4 | SMALL, SEDAN, LUXURY 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/logging/Command.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command.logging; 2 | 3 | public interface Command { 4 | void execute(); 5 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author : CodeVillains 3 | * @Description : 한 클래스의 인터페이스를 클라이언트에서 사용하고자 하는 다른 인터페이스로 변환 4 | */ 5 | package net.harunote.pattern.adapter; -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/CalculationStrategy.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | public interface CalculationStrategy { 4 | 5 | public int calculate(int num1, int num2); 6 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/logging/Invoker.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command.logging; 2 | 3 | public class Invoker { 4 | public void executeCommand(Command command) { 5 | command.execute(); 6 | } 7 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/Command.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public interface Command { 8 | 9 | void execute(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/logging/Logger.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command.logging; 2 | 3 | public class Logger { 4 | public void log(String message) { 5 | System.out.println("Logging: " + message); 6 | } 7 | } -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/NyStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class NyStyleClamPizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/NyStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class NyStyleVeggiePizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoStyleClamPizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/NyStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class NyStylePepperoniPizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoStyleVeggiePizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoStylePepperoniPizza extends Pizza { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/MediaPlayer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public interface MediaPlayer { 8 | public void play(String audioType, String fileName); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/CondimentDecorator.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public abstract class CondimentDecorator extends Beverage { 8 | public abstract String getDescription(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author : CodeVillains 3 | * @Description : 인스턴스를 계속만들어 내는 것이 아닌, 동일 인스턴스를 사용하게 해야할 경우 사용된다. 4 | * 공용으로 사용하는 클래스(환경 설정 클래스나 커넥션 풀 등)와 같이 프로그램의 종료 시점까지 단 하나의 인스턴스만을 생성하고 재 사용한다거나 관리할 때 유용하다. 5 | */ 6 | package net.harunote.pattern.singleton; -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/consumer/PrintLength.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.consumer; 2 | 3 | import java.util.function.Consumer; 4 | 5 | class PrintLength implements Consumer { 6 | public void accept(String color) { 7 | System.out.println(color.length()); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/input/TextInput.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.input; 2 | 3 | class TextInput { 4 | static String textInput = ""; 5 | public void add(char c) { 6 | textInput += c; 7 | } 8 | 9 | public String getValue() { 10 | return textInput; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.properties= 2 | log4j.rootLogger=INFO, stdout 3 | 4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 5 | log4j.appender.stdout.Target=System.out 6 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.stdout.layout.ConversionPattern= %-5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/lambda/runnable/RunnableThread.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.lambda.runnable; 2 | 3 | public class RunnableThread implements Runnable { 4 | @Override 5 | public void run() { 6 | System.out.println("Runnable 구현 " + Thread.currentThread().getName()); 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/AdvancedMediaPlayer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public interface AdvancedMediaPlayer { 8 | public void playVlc(String fileName); 9 | 10 | public void playMp4(String fileName); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/DarkRoast.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | public class DarkRoast extends Beverage { 4 | 5 | public DarkRoast() { 6 | description = "다크로스트"; 7 | } 8 | 9 | @Override 10 | public double cost() { 11 | return 2.8; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/AddOperation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class AddOperation implements CalculationStrategy{ 7 | @Override 8 | public int calculate(int num1, int num2) { 9 | return num1 + num2; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/DivideOperation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class DivideOperation implements CalculationStrategy{ 7 | @Override 8 | public int calculate(int num1, int num2) { 9 | return num1 / num2; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/MultiplyOperation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class MultiplyOperation implements CalculationStrategy{ 7 | @Override 8 | public int calculate(int num1, int num2) { 9 | return num1 * num2; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/SubstractOperation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class SubstractOperation implements CalculationStrategy{ 7 | @Override 8 | public int calculate(int num1, int num2) { 9 | return num1 - num2; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Beverage.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public abstract class Beverage { 8 | String description = "제목없음"; 9 | 10 | public String getDescription() { 11 | return description; 12 | } 13 | 14 | public abstract double cost(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Decaf.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Decaf extends Beverage { 8 | 9 | public Decaf() { 10 | description = "디카프"; 11 | } 12 | 13 | @Override 14 | public double cost() { 15 | return 1.2; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/SedanCar.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | public class SedanCar extends Car { 4 | SedanCar() { 5 | super(CarType.SEDAN); 6 | construct(); 7 | } 8 | @Override 9 | protected void construct() { 10 | System.out.println("Building sedan car"); 11 | // do something 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Espresso.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Espresso extends Beverage { 8 | public Espresso() { 9 | description = "에스프레소"; 10 | } 11 | 12 | @Override 13 | public double cost() { 14 | return 1.99; 15 | } 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/HouseBlend.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class HouseBlend extends Beverage { 8 | public HouseBlend() { 9 | description = "하우스 브렌드 커피"; 10 | } 11 | 12 | @Override 13 | public double cost() { 14 | return .89; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/LuxuryCar.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | public class LuxuryCar extends Car { 4 | LuxuryCar() { 5 | super(CarType.LUXURY); 6 | construct(); 7 | } 8 | 9 | @Override 10 | protected void construct() { 11 | System.out.println("Building luxury Car"); 12 | // do something 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/SmallCar.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | 4 | public class SmallCar extends Car { 5 | SmallCar() { 6 | super(CarType.SMALL); 7 | construct(); 8 | } 9 | 10 | @Override 11 | protected void construct() { 12 | System.out.println("Building small car"); 13 | // do something 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/Singleton.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.singleton; 2 | 3 | public class Singleton { 4 | private Singleton() { 5 | } 6 | 7 | private static class SingletonHolder { 8 | private static final Singleton INSTANCE = new Singleton(); 9 | } 10 | 11 | public static Singleton getInstance() { 12 | return SingletonHolder.INSTANCE; 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/ReverseString.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | public class ReverseString { 4 | public static void main(String[] args) { 5 | ReverseString rs = new ReverseString(); 6 | System.out.println(rs.reverseStr("ABCDefg")); 7 | } 8 | 9 | private String reverseStr(String str) { 10 | return new StringBuilder(str).reverse().toString(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author : CodeVillains 3 | * @Description : 팩토리 패턴 4 | * - Object 생성시 new 를 사용하여 생성할 경우 Concrete class 를 의존하여 코딩하기 때문에 결합도가 매우 높다. (수정시 의존도가 높고 유연성이 떨어짐) 5 | * - Factorty Pattern을 통해 실제 사용하는 곳에서 Concrete class를 정하지 않고 Factory 를 사용하여 의존성을 받도록 하여 Concrete class를 6 | * 전혀 의존하지 않도록 한다 (DIP : Depencency Inversion Priciple) 7 | */ 8 | package net.harunote.pattern.factory; -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/SellStock.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class SellStock implements Command { 8 | private Stock stock; 9 | 10 | public SellStock(Stock stock) { 11 | this.stock = stock; 12 | } 13 | 14 | @Override 15 | public void execute() { 16 | stock.sell(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/BuyStock.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class BuyStock implements Command { 8 | 9 | private Stock stock; 10 | 11 | public BuyStock(Stock stock) { 12 | this.stock = stock; 13 | } 14 | 15 | @Override 16 | public void execute() { 17 | stock.buy(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/input/NumericInput.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.input; 2 | 3 | class NumericInput extends TextInput { 4 | static String numberInput = ""; 5 | 6 | @Override 7 | public void add(char c) { 8 | if (Character.isDigit(c)){ 9 | numberInput += c; 10 | } 11 | } 12 | 13 | @Override 14 | public String getValue() { 15 | return numberInput; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/logging/LoggerApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command.logging; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class LoggerApp { 7 | public static void main(String[] args) { 8 | Logger logger = new Logger(); 9 | Command logCommand = new LogCommand(logger, "Hello, World!"); 10 | Invoker invoker = new Invoker(); 11 | invoker.executeCommand(logCommand); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/ReverseString2.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class ReverseString2 { 7 | public static void main(String[] args) { 8 | String str = "ABCDefg"; 9 | // 문자 배열로 변환한 뒤 역순으로 출력한다. 10 | char chars[] = str.toCharArray(); 11 | for(int i= chars.length-1; i >= 0; i--) { 12 | System.out.print(chars[i]); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/input/UserInput.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.input; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class UserInput { 8 | public static void main(String[] args) { 9 | TextInput input = new NumericInput(); 10 | input.add('a'); 11 | input.add('b'); 12 | input.add('z'); 13 | input.add('z'); 14 | System.out.println(input.getValue()); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/Mp4Player.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Mp4Player implements AdvancedMediaPlayer { 8 | @Override 9 | public void playVlc(String fileName) { 10 | 11 | } 12 | 13 | @Override 14 | public void playMp4(String fileName) { 15 | System.out.println("Playing mp4 file. name : " + fileName); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/Calculation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class Calculation { 7 | private CalculationStrategy strategy; 8 | 9 | public Calculation(CalculationStrategy strategy) { 10 | this.strategy = strategy; 11 | } 12 | 13 | public int executeStrategy(int num1, int num2) { 14 | return strategy.calculate(num1, num2); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/logging/LogCommand.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command.logging; 2 | 3 | public class LogCommand implements Command { 4 | private Logger logger; 5 | private String message; 6 | 7 | public LogCommand(Logger logger, String message) { 8 | this.logger = logger; 9 | this.message = message; 10 | } 11 | 12 | @Override 13 | public void execute() { 14 | logger.log(message); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/predicate/Tshirt.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.predicate; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.ToString; 6 | 7 | /** 8 | * @author CodeVillains 9 | */ 10 | @Getter 11 | @ToString 12 | public class Tshirt { 13 | private int price; 14 | private String color; 15 | 16 | public Tshirt(int price, String color) { 17 | this.price = price; 18 | this.color = color; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/VlcPlayer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class VlcPlayer implements AdvancedMediaPlayer { 8 | @Override 9 | public void playVlc(String fileName) { 10 | System.out.println("Playing VLC File. name = " + fileName); 11 | 12 | } 13 | 14 | @Override 15 | public void playMp4(String fileName) { 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/actor/PrizeYearComparator.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort.actor; 2 | 3 | import java.util.Comparator; 4 | 5 | // 수상 연도별로 정렬하기 위해 Comparator 인터페이스를 구현 6 | class PrizeYearComparator implements Comparator { 7 | 8 | public int compare(Object o1, Object o2) { 9 | int year1 = ((Actor) o1).prizeYear; 10 | int year2 = ((Actor) o2).prizeYear; 11 | return year1 > year2 ? -1 : (year1 == year2 ? 0 : 1); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/NyStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class NyStyleCheesePizza extends Pizza { 8 | public NyStyleCheesePizza() { 9 | name = "NY Style Sauce and Cheese Pizza"; 10 | dough = "Thin Crust Dough"; 11 | sauce = "Marinara Sauce"; 12 | 13 | toppings.add("Grated Reggiano Cheese"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/ExecutionExampleApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | public class ExecutionExampleApp { 4 | 5 | public static void main(String[] args) { 6 | run(() -> System.out.println("Hello, world!")); 7 | } 8 | 9 | public static void run(Runnable runnable) { 10 | runnable.run(); 11 | } 12 | 13 | // Thread thread = new Thread(() -> System.out.println("Hello, world!")); 14 | // thread.start(); 15 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/function/StringLengthExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.function; 2 | 3 | import java.util.function.Function; 4 | 5 | public class StringLengthExample { 6 | public static void main(String[] args) { 7 | Function stringLength = s -> s.length(); 8 | 9 | String str = "Hello, World!"; 10 | int length = stringLength.apply(str); 11 | 12 | System.out.println("\""+str + "\" 문자의 길이는 " + length + " 입니다."); 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/StrToInt.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class StrToInt { 8 | public int getStrToInt(String str) { 9 | int result = Integer.parseInt(str); 10 | return result; 11 | } 12 | //아래는 테스트로 출력해 보기 위한 코드입니다. 13 | public static void main(String args[]) { 14 | StrToInt strToInt = new StrToInt(); 15 | System.out.println(strToInt.getStrToInt("-1234")); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/consumer/PrintLengthApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.consumer; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * @author CodeVillains 8 | */ 9 | public class PrintLengthApp { 10 | public static void main(String[] args) { 11 | List colors = Arrays.asList("blue", "green", "white", "red", "yellow", "bluesky"); 12 | PrintLength printLength = new PrintLength(); 13 | colors.forEach(printLength); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/Calculator.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | */ 8 | public class Calculator { 9 | private BiFunction operation; 10 | 11 | public void setOperation(BiFunction operation) { 12 | this.operation = operation; 13 | } 14 | 15 | public int calculate(int a, int b) { 16 | return operation.apply(a, b); 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/facade/FacedeApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.facade; 2 | 3 | public class FacedeApp { 4 | public static void main(String[] args) { 5 | String tableName="Company"; 6 | //generating MySql HTML report and Oracle PDF report using Facade 7 | HelperFacade.generateReport(HelperFacade.DBTypes.MYSQL, HelperFacade.ReportTypes.HTML, tableName); 8 | HelperFacade.generateReport(HelperFacade.DBTypes.ORACLE, HelperFacade.ReportTypes.PDF, tableName); 9 | 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/TestFactoryPattern.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | public class TestFactoryPattern { 4 | 5 | public static void main(String[] args) { 6 | // Car car1 = CarFactory.buildCar(CarType.SMALL); 7 | // Car car2 = CarFactory.buildCar(CarType.SEDAN); 8 | System.out.println(CarFactory.buildCar(CarType.SMALL)); 9 | System.out.println(CarFactory.buildCar(CarType.SEDAN)); 10 | System.out.println(CarFactory.buildCar(CarType.LUXURY)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/Stock.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Stock { 8 | 9 | private String name = "ABC"; 10 | private int quantity = 10; 11 | 12 | public void buy() { 13 | System.out.println("Stock [Name : " + name + " Quantity : " + quantity + "] bought"); 14 | } 15 | 16 | public void sell() { 17 | System.out.println("Stock [Name : " + name + " Quantity : " + quantity + "] sold"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/TreeSetDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.Set; 4 | import java.util.TreeSet; 5 | 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 10 | */ 11 | public class TreeSetDemo { 12 | public static void main(String[] args) { 13 | // 트리 집합을 만든다. 14 | Set ts = new TreeSet(); 15 | // 트리 집합에 요소들을 추가한다. 16 | ts.add("C"); 17 | ts.add("A"); 18 | ts.add("B"); 19 | ts.add("E"); 20 | ts.add("F"); 21 | ts.add("D"); 22 | System.out.println(ts); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/legacy/Car.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.legacy; 2 | 3 | public class Car { 4 | public static final String SMALL_CAR = "small"; 5 | public static final String SEDAN_CAR = "sedan"; 6 | public static final String LUXURY_CAR = "luxury"; 7 | 8 | private String productName; 9 | 10 | public Car(String name) { 11 | this.productName = name; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return "Car productName = '" + productName + '\''; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/template/application/GlassHouse.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.template.application; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | @Slf4j 8 | public class GlassHouse extends HouseTemplate { 9 | 10 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 11 | 12 | @Override 13 | public void buildWalls() { 14 | logger.info("유리벽을 만들었다."); 15 | } 16 | 17 | @Override 18 | public void buildPillars() { 19 | logger.info("유리 기둥을 만들었다."); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/AdapterPatternApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class AdapterPatternApp { 8 | public static void main(String[] args) { 9 | AudioPlayer audioPlayer = new AudioPlayer(); 10 | 11 | 12 | audioPlayer.play("mp3", "beyond the horizon.mp3"); 13 | audioPlayer.play("mp4", "alone.mp4"); 14 | audioPlayer.play("vlc", "far far away.vlc"); 15 | audioPlayer.play("avi", "mind me.avi"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/template/application/WoodenHouse.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.template.application; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | @Slf4j 8 | public class WoodenHouse extends HouseTemplate { 9 | 10 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 11 | 12 | @Override 13 | public void buildWalls() { 14 | logger.info("나무벽을 만들었다."); 15 | } 16 | 17 | @Override 18 | public void buildPillars() { 19 | logger.info("나무 기둥을 만들었다."); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public abstract class PizzaStore { 8 | 9 | public Pizza orderPizza(String type) { 10 | Pizza pizza; 11 | 12 | pizza = createPizza(type); 13 | 14 | pizza.prepare(); 15 | pizza.bake(); 16 | pizza.cut(); 17 | pizza.box(); 18 | 19 | return pizza; 20 | } 21 | 22 | protected abstract Pizza createPizza(String type); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Soy.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Soy extends CondimentDecorator { 8 | Beverage beverage; 9 | 10 | public Soy(Beverage beverage) { 11 | this.beverage = beverage; 12 | } 13 | 14 | @Override 15 | public String getDescription() { 16 | return beverage.getDescription() + ", 두유 "; 17 | } 18 | 19 | @Override 20 | public double cost() { 21 | return .70 + beverage.cost(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/LinkedHashSetDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.LinkedHashSet; 4 | import java.util.Set; 5 | 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 10 | */ 11 | class LinkedHashSetDemo { 12 | public static void main(String[] args) { 13 | Set linkHashSet = new LinkedHashSet(); 14 | linkHashSet.add("B"); 15 | linkHashSet.add("A"); 16 | linkHashSet.add("D"); 17 | linkHashSet.add("E"); 18 | linkHashSet.add("C"); 19 | linkHashSet.add("F"); 20 | System.out.println(linkHashSet); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Mocha.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Mocha extends CondimentDecorator { 8 | Beverage beverage; 9 | 10 | public Mocha(Beverage beverage) { 11 | this.beverage = beverage; 12 | } 13 | 14 | @Override 15 | public String getDescription() { 16 | return beverage.getDescription() + ", 모카"; 17 | } 18 | 19 | @Override 20 | public double cost() { 21 | return .20 + beverage.cost(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | bin/ 16 | !**/src/main/**/bin/ 17 | !**/src/test/**/bin/ 18 | 19 | ### IntelliJ IDEA ### 20 | .idea 21 | *.iws 22 | *.iml 23 | *.ipr 24 | out/ 25 | !**/src/main/**/out/ 26 | !**/src/test/**/out/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/Whip.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class Whip extends CondimentDecorator { 8 | Beverage beverage; 9 | 10 | public Whip(Beverage beverage) { 11 | this.beverage = beverage; 12 | } 13 | 14 | 15 | @Override 16 | public String getDescription() { 17 | return beverage.getDescription() + ", 휘핑크림"; 18 | 19 | } 20 | 21 | @Override 22 | public double cost() { 23 | return .50 + beverage.cost(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/Product.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort; 2 | 3 | public class Product { 4 | 5 | public Product(String prdId, Integer prdSize) { 6 | this.prdId = prdId; 7 | this.prdSize = prdSize; 8 | } 9 | 10 | private String prdId; 11 | private Integer prdSize; 12 | 13 | public String getPrdId() { 14 | return prdId; 15 | } 16 | public void setPrdId(String prdId) { 17 | this.prdId = prdId; 18 | } 19 | public Integer getPrdSize() { 20 | return prdSize; 21 | } 22 | public void setPrdSize(Integer prdSize) { 23 | this.prdSize = prdSize; 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/consumer/ConsumerExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.consumer; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Consumer; 6 | 7 | public class ConsumerExample { 8 | public static void main(String[] args) { 9 | List colors = Arrays.asList("blue", "green", "white", "red", "yellow", "bluesky"); 10 | 11 | // Consumer 인터페이스를 구현한 람다식 12 | Consumer printLength = (color) -> System.out.println(color.length()); 13 | 14 | colors.forEach(printLength); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/lambda/runnable/RunnableInterfaceApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.lambda.runnable; 2 | 3 | public class RunnableInterfaceApp { 4 | public static void main(String[] args) { 5 | RunnableThread runnableThread = new RunnableThread(); 6 | 7 | // 람다 표현식을 이용한 스레드 새성 8 | Thread thread1 = new Thread(() -> System.out.println("람다 표현식 " + Thread.currentThread().getName())); 9 | 10 | // 메서드 참조를 사용한 스레드 생성 11 | Thread thread2 = new Thread(runnableThread::run); 12 | 13 | thread1.start(); 14 | thread2.start(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/EagerSingleton.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.singleton; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : Eager initialization - 정적초기화 구문을 통해서 JVM이 클래스 로딩 타이밍에 인스턴스를 생성하도록 한다. 6 | * 이미 인스턴스를 생성 했기 때문에 리턴만 해주면 된다. 단, 사용하지 않는다면 이것도 낭비다 7 | */ 8 | public class EagerSingleton { 9 | private static volatile EagerSingleton instance = new EagerSingleton(); 10 | 11 | // private constructor 12 | private EagerSingleton() { 13 | 14 | } 15 | 16 | public static EagerSingleton getInstance() { 17 | return instance; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/HashSetDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | //HashSet을 설명한다. 7 | 8 | /** 9 | * @Author : CodeVillains 10 | * @Description : 11 | */ 12 | public class HashSetDemo { 13 | 14 | public static void main(String args[]) { 15 | // 해시 집합을 생성한다. 16 | Set hs = new HashSet<>(); 17 | // 해시 집합에 요소를 추가한다. 18 | hs.add("B"); 19 | hs.add("A"); 20 | hs.add("D"); 21 | hs.add("E"); 22 | hs.add("C"); 23 | hs.add("F"); 24 | hs.toString(); 25 | 26 | System.out.println(hs); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/predicate/TshirtPredicate.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.predicate; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | @FunctionalInterface 7 | interface TshirtPredicate { 8 | public boolean test(Tshirt t); 9 | } 10 | 11 | class TshirtColorPredicate implements TshirtPredicate { 12 | public boolean test(Tshirt tshirt) { 13 | return "red".equals(tshirt.getColor()); 14 | } 15 | } 16 | 17 | class TshirtPricePredicate implements TshirtPredicate { 18 | public boolean test(Tshirt tshirt) { 19 | return tshirt.getPrice() > 300; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/Broker.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 9 | */ 10 | public class Broker { 11 | 12 | private List commandList = new ArrayList<>(); 13 | 14 | public void takeOrder(Command command) { 15 | commandList.add(command); 16 | } 17 | 18 | public void placeOrders() { 19 | for (Command command : commandList) { 20 | command.execute(); 21 | } 22 | 23 | commandList.clear(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/template/HousingApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.template; 2 | 3 | 4 | import net.harunote.pattern.template.application.GlassHouse; 5 | import net.harunote.pattern.template.application.HouseTemplate; 6 | import net.harunote.pattern.template.application.WoodenHouse; 7 | 8 | public class HousingApp { 9 | 10 | public static void main(String[] args) { 11 | HouseTemplate houseType = new WoodenHouse(); 12 | //using template method 13 | houseType.buildHouse(); 14 | System.out.println("************"); 15 | 16 | houseType = new GlassHouse(); 17 | houseType.buildHouse(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoStyleCheesePizza extends Pizza { 8 | public ChicagoStyleCheesePizza() { 9 | name = "Chicago Style Deep Dish Cheese Pizza"; 10 | dough = "Extra Think Crust Dough"; 11 | sauce = "Plum Tomato Sauce"; 12 | 13 | toppings.add("Shredded Mozzarella Cheese"); 14 | } 15 | 16 | void cut() { 17 | System.out.println("Cutting the pizza into square slices"); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoStylePizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoStylePizza extends Pizza { 8 | public ChicagoStylePizza() { 9 | name = "Chicago Style Deep Dish Cheese Pizza"; 10 | dough = "Extra Thick Crust Dough"; 11 | sauce = "Plum Tomato Sauce"; 12 | 13 | toppings.add("Shredded Mozzarella Cheese"); 14 | } 15 | 16 | @Override 17 | void cut() { 18 | System.out.println("Cutting the pizza into square slices"); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/supplier/RandomNumberSupplier.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.supplier; 2 | 3 | import java.util.Random; 4 | import java.util.function.Supplier; 5 | 6 | public class RandomNumberSupplier { 7 | public static void main(String[] args) { 8 | Supplier randomNumberSupplier = () -> new Random().nextInt(11); 9 | 10 | int randomNumber1 = randomNumberSupplier.get(); 11 | int randomNumber2 = randomNumberSupplier.get(); 12 | 13 | System.out.println("Random number 1: " + randomNumber1); 14 | System.out.println("Random number 2: " + randomNumber2); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/CarFactory.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | public class CarFactory { 4 | public static Car buildCar(CarType model) { 5 | Car car = null; 6 | 7 | switch (model) { 8 | case SMALL: 9 | car = new SmallCar(); 10 | break; 11 | case SEDAN: 12 | car = new SedanCar(); 13 | break; 14 | case LUXURY: 15 | car = new LuxuryCar(); 16 | break; 17 | default: 18 | break; 19 | } 20 | 21 | return car; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/lambda/comparator/TshirtSorterLambda.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.lambda.comparator; 2 | 3 | import net.harunote.java8.functional.predicate.Tshirt; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * @author CodeVillains 9 | */ 10 | public class TshirtSorterLambda { 11 | public static void main(String[] args) { 12 | Tshirt[] tshirts = {new Tshirt(10000, "red"), new Tshirt(5000, "blue"), new Tshirt(8000, "green")}; 13 | 14 | Arrays.sort(tshirts, (t1, t2) -> t1.getPrice() - t2.getPrice()); 15 | for (Tshirt tshirt : tshirts) { 16 | System.out.println(tshirt); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/command/CommandPatternApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.command; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : Command Pattern - 요청을 하는 객체와 그 요청을 수행하는 객체를 분리하여 메소드 호출을 캡슐화 한다 6 | */ 7 | public class CommandPatternApp { 8 | public static void main(String[] args) { 9 | Stock stock = new Stock(); 10 | 11 | BuyStock buyStock = new BuyStock(stock); 12 | SellStock sellStock = new SellStock(stock); 13 | 14 | Broker broker = new Broker(); 15 | 16 | broker.takeOrder(buyStock); 17 | broker.takeOrder(sellStock); 18 | 19 | broker.placeOrders(); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/car/Car.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.car; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | public abstract class Car { 7 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 8 | private CarType model; 9 | 10 | public Car(CarType model) { 11 | this.model = model; 12 | arrangePart(); 13 | } 14 | 15 | protected void arrangePart() { 16 | // Do one time processing here 17 | logger.info("Do one time processing here"); 18 | } 19 | 20 | // Do subclass level processing in this method 21 | protected abstract void construct(); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/arrays/ArraySort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 10 | */ 11 | public class ArraySort { 12 | public static void main(String[] args) { 13 | Integer[] myArray = { 5, 2, 7, 3, 9 }; 14 | Arrays.sort(myArray); 15 | 16 | System.out.println(Arrays.toString(myArray)); 17 | 18 | 19 | List myList = Arrays.asList(myArray); 20 | Collections.reverse(myList); 21 | 22 | //myList.toArray(myArray); 23 | 24 | 25 | System.out.println(Arrays.toString(myArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/PizzaStoreTestDrive.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class PizzaStoreTestDrive { 8 | public static void main(String[] args) { 9 | PizzaStore nyStore = new NyPizzaStore(); 10 | PizzaStore chicagoStore = new ChicagoPizzaStore(); 11 | 12 | Pizza pizza = nyStore.orderPizza("cheese"); 13 | System.out.println("first ordered " + pizza.getName() + " from ny store\n"); 14 | 15 | Pizza pizza1 = chicagoStore.orderPizza("cheese"); 16 | System.out.println("second ordered " + pizza1.getName() + " from chicago store"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/facade/MySqlHelper.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.facade; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.sql.Connection; 7 | 8 | public class MySqlHelper { 9 | 10 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 11 | 12 | public static Connection getMySqlDBConnection(){ 13 | // get DB connection using connection parameters 14 | return null; 15 | } 16 | 17 | public void generateMySqlPDFReport(String tableName, Connection con){ 18 | logger.info("MySQL DB의 테이블에서 PDF를 생성한다."); 19 | } 20 | 21 | public void generateMySqlHTMLReport(String tableName, Connection con){ 22 | logger.info("MySQL DB의 테이블에서 HTML를 생성한다."); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/SortingExampleApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | public class SortingExampleApp { 7 | 8 | public static void main(String[] args) { 9 | Integer[] numbers = {10, 9, 2, 5, 7, 6}; 10 | 11 | // 오름차순 정렬 12 | sort(numbers, (a, b) -> a.compareTo(b)); 13 | System.out.println(Arrays.toString(numbers)); 14 | 15 | // 내림차순 정렬 16 | sort(numbers, (a, b) -> b.compareTo(a)); 17 | System.out.println(Arrays.toString(numbers)); 18 | } 19 | 20 | public static void sort(T[] array, Comparator comparator) { 21 | Arrays.sort(array, comparator); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/arrays/ArrayIndexPosition.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.arrays; 2 | 3 | /** 4 | * @Author CodeVillains 5 | * main 메소드에 최소 10개 이상의 요소로 구성된 integer array를 정의 한 후 해당 array의 최소 값이 위치한 자리수와 그 값을 출력한다. 6 | */ 7 | public class ArrayIndexPosition { 8 | public static void main(String[] args) { 9 | int a[] = new int[]{12, 44, 23, 56, 9, 23, 78, 13}; 10 | 11 | int min = a[0]; 12 | int index = 0; 13 | 14 | for (int i = 0; i < a.length; i++) { 15 | if (min > a[i]) { 16 | min = a[i]; 17 | index = i; 18 | } 19 | } 20 | 21 | System.out.println("Index position of Smallest value in a given array is : " + index); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/NyPizzaStore.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class NyPizzaStore extends PizzaStore { 8 | @Override 9 | protected Pizza createPizza(String type) { 10 | if (type.equals("cheese")) { 11 | return new NyStyleCheesePizza(); 12 | } else if (type.equals("veggie")) { 13 | return new NyStyleVeggiePizza(); 14 | } else if (type.equals("clam")) { 15 | return new NyStyleClamPizza(); 16 | } else if (type.equals("pepperoni")) { 17 | return new NyStylePepperoniPizza(); 18 | } else { 19 | return null; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/lambda/runnable/RunnableLambda.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.lambda.runnable; 2 | 3 | public class RunnableLambda { 4 | public static void main(String[] args) { 5 | Runnable runnable1 = () -> System.out.println("Lambda 표현식을 이용한 Runnable"); 6 | Runnable runnable2 = new Runnable() { 7 | @Override 8 | public void run() { 9 | System.out.println("익명 클래스를 이용한 Runnable"); 10 | } 11 | }; 12 | 13 | processRunnable(runnable1); 14 | processRunnable(runnable2); 15 | processRunnable(() -> System.out.println("메서드에 직접 전달 Runnable")); 16 | 17 | } 18 | 19 | private static void processRunnable(Runnable runnable) { 20 | runnable.run(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/LazySingleton.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.singleton; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 요청이 있을 때에 생성되는 인스턴스. 즉 사용되는 시점에 인스턴스를 생성한다. 6 | */ 7 | public class LazySingleton { 8 | private static volatile LazySingleton instance = null; 9 | 10 | private LazySingleton() { 11 | 12 | } 13 | 14 | public static LazySingleton getInstance(){ 15 | if (instance == null) { 16 | // 동시에 두개의 스레드가 instance == null 에 접근할 경우 두개의 인스턴스가 생성될 수 도 있다 17 | // See LazySingletonDoubleCheckLocking 18 | synchronized (LazySingleton.class) { 19 | instance = new LazySingleton(); 20 | } 21 | } 22 | 23 | return instance; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/EqualString.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class EqualString { 8 | public static void main(String[] args) { 9 | String a = "test"; 10 | String b = new String("test"); 11 | String c = "test"; 12 | 13 | System.out.println("equals string a,b= " + (a==b)); // false 14 | System.out.println("equals string b,c= " + (c==b)); // false 15 | System.out.println("equals string a,c= " + (a==c)); // true 16 | 17 | StringBuffer ab = new StringBuffer(); 18 | StringBuffer bb = ab.append("test"); 19 | 20 | System.out.println("equals stringbuffer = " + (ab == bb)); // true 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/PrintTriangle.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * printTriangle 메소드는 양의 정수 num을 매개변수로 입력받습니다. 6 | * 다음을 참고해 *(별)로 높이가 num인 삼각형을 문자열로 리턴하는 printTriangle 메소드를 완성하시오 7 | * printTriangle이 return하는 String은 개행문자('\n')로 끝나야 합니다. 8 | */ 9 | 10 | public class PrintTriangle { 11 | public String printTriangle(int num){ 12 | StringBuffer sb = new StringBuffer(); 13 | 14 | String result = ""; 15 | for (int i = 0; i < num; i++) { 16 | result += "*"; 17 | sb.append(result).append("\n"); 18 | } 19 | return sb.toString(); 20 | } 21 | 22 | // 아래는 테스트로 출력해 보기 위한 코드입니다. 23 | public static void main(String[] args) { 24 | PrintTriangle pt = new PrintTriangle(); 25 | System.out.println( pt.printTriangle(3) ); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class ChicagoPizzaStore extends PizzaStore { 8 | @Override 9 | protected Pizza createPizza(String type) { 10 | if (type.equals("cheese")) { 11 | return new ChicagoStyleCheesePizza(); 12 | } else if (type.equals("veggie")) { 13 | return new ChicagoStyleVeggiePizza(); 14 | } else if (type.equals("clam")) { 15 | return new ChicagoStyleClamPizza(); 16 | } else if (type.equals("pepperoni")) { 17 | return new ChicagoStylePepperoniPizza(); 18 | } else { 19 | return null; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/actor/Actor.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort.actor; 2 | 3 | class Actor implements Comparable { 4 | 5 | String name; 6 | String title; 7 | int prizeYear; 8 | 9 | // Constructor 10 | public Actor(String name, String title, int birthYear) { 11 | this.prizeYear = birthYear; 12 | this.name = name; 13 | this.title = title; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return "수상 배우 목록 {" + "배우 = " + name + ", 영화 제목 [" + title + "]" + ", 청룡영화제 남우주연상 수상 연도=" 19 | + prizeYear + '}'; 20 | } 21 | 22 | // 정렬될 때 배우 이름 기준으로 오름차순 정렬한다. 23 | @Override 24 | public int compareTo(Object o) { 25 | return name.compareTo(((Actor) o).name); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/AudioPlayer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class AudioPlayer implements MediaPlayer { 8 | MediaAdapter mediaAdapter; 9 | 10 | @Override 11 | public void play(String audioType, String fileName) { 12 | if (audioType.equalsIgnoreCase("mp3")) { 13 | System.out.println("Playing mp3 file. name : " + fileName); 14 | } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) { 15 | mediaAdapter = new MediaAdapter(audioType); 16 | mediaAdapter.play(audioType, fileName); 17 | } else { 18 | System.out.println("Invalid media. " + audioType + " format not supported"); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/InitializationOnDemandHolderIdiom.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.singleton; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : static inner class 를 이용하여 instance를 생성한다. 6 | * jvm 의 class loader의 매커니즘과 class의 load 시점을 이용하여 내부 class를 생성시킴으로 thread 간의 동기화 문제를 해결한다. 7 | */ 8 | public class InitializationOnDemandHolderIdiom { 9 | private InitializationOnDemandHolderIdiom() {} 10 | 11 | private static class Singleton { 12 | private static final InitializationOnDemandHolderIdiom instance = new InitializationOnDemandHolderIdiom(); 13 | } 14 | 15 | public static InitializationOnDemandHolderIdiom getInstance() { 16 | System.out.println("InitializationOnDemandHolderIdiom create instance"); 17 | return Singleton.instance; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/singleton/LazySingletonDoubleCheckLocking.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.singleton; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class LazySingletonDoubleCheckLocking { 8 | private static volatile LazySingletonDoubleCheckLocking instance = null; 9 | 10 | private LazySingletonDoubleCheckLocking(){ 11 | 12 | } 13 | 14 | public static LazySingletonDoubleCheckLocking getInstance() { 15 | if (instance == null) { 16 | synchronized (LazySingletonDoubleCheckLocking.class) { 17 | // Double check locking 18 | if (instance == null) { 19 | instance = new LazySingletonDoubleCheckLocking(); 20 | } 21 | } 22 | } 23 | 24 | return instance; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/ListSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ListSort { 8 | 9 | public static void main(String args[]) { 10 | List listObject = new ArrayList(); 11 | listObject.add("z"); 12 | listObject.add("a"); 13 | listObject.add("f"); 14 | listObject.add("c"); 15 | 16 | System.out.println("##기본출력 : " + listObject); 17 | // 문자열순으로 정렬 18 | Collections.sort(listObject, String.CASE_INSENSITIVE_ORDER); 19 | 20 | System.out.println("##순차정렬 : " + listObject); 21 | // 역순으로 정렬 22 | Collections.sort(listObject, Collections.reverseOrder()); 23 | System.out.println("##역순정렬 : " + listObject); 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/ListSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ListSort { 8 | 9 | public static void main(String args[]) { 10 | List listObject = new ArrayList(); 11 | listObject.add("z"); 12 | listObject.add("a"); 13 | listObject.add("f"); 14 | listObject.add("c"); 15 | 16 | System.out.println("##기본출력 : " + listObject); 17 | // 문자열순으로 정렬 18 | Collections.sort(listObject, String.CASE_INSENSITIVE_ORDER); 19 | 20 | System.out.println("##순차정렬 : " + listObject); 21 | // 역순으로 정렬 22 | Collections.sort(listObject, Collections.reverseOrder()); 23 | System.out.println("##역순정렬 : " + listObject); 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/strategy/CalculationDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.strategy; 2 | 3 | /** 4 | * @author CodeVillains 5 | */ 6 | public class CalculationDemo { 7 | public static void main(String[] args) { 8 | Calculation add = new Calculation(new AddOperation()); 9 | System.out.println("8 + 4 = " + add.executeStrategy(8, 4)); 10 | 11 | Calculation substract = new Calculation(new SubstractOperation()); 12 | System.out.println("8 - 4 = " + substract.executeStrategy(8, 4)); 13 | 14 | Calculation multiply = new Calculation(new MultiplyOperation()); 15 | System.out.println("8 * 4 = " + multiply.executeStrategy(8, 4)); 16 | 17 | Calculation divide = new Calculation(new DivideOperation()); 18 | System.out.println("8 / 4 = " + divide.executeStrategy(8, 4)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/EvenOrOdd.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : evenOrOdd 메소드는 int형 num을 매개변수로 받습니다. num이 짝수일 경우 "Even"을 반환하고 홀수인 경우 "Odd"를 반환하도록 6 | * evenOrOdd에 코드를 작성해 보세요. num은 0이상의 정수이며, num이 음수인 경우는 없습니다. 7 | */ 8 | public class EvenOrOdd { 9 | 10 | public static void main(String[] args) { 11 | int num = 4; 12 | 13 | EvenOrOdd eo = new EvenOrOdd(); 14 | System.out.println(num + " 은(는)" + eo.evenOrOdd(num) + " 입니다"); 15 | 16 | // return (num % 2 == 0) ? "Even" : "Odd"; 17 | } 18 | 19 | public String evenOrOdd(int num) { 20 | String result = ""; 21 | if (num % 2 == 0) { 22 | result = "Even"; 23 | } else { 24 | result = "Odd"; 25 | } 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/MappingExampleApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | import java.util.stream.Collectors; 7 | 8 | public class MappingExampleApp { 9 | 10 | public static void main(String[] args) { 11 | List words = Arrays.asList("green", "blue", "yellow", "red", "white"); 12 | 13 | List wordLengths = map(words, String::length); 14 | System.out.println(wordLengths); 15 | } 16 | // map 메서드를 구현할 때 Function 인터페이스를 파라미터로 받아서 Stream.map 메서드를 호출하고 있다. 17 | // 이를 통해 각 단어의 길이를 구하고, 이를 새로운 리스트에 담아 반환할 수 있다. 18 | public static List map(List list, Function mapper) { 19 | return list.stream().map(mapper).collect(Collectors.toList()); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/EvenNumberPredicate.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Predicate; 6 | import java.util.stream.Collectors; 7 | 8 | /** 9 | * @author CodeVillains 10 | */ 11 | public class EvenNumberPredicate { 12 | public static void main(String[] args) { 13 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 14 | Predicate evenNumber = n -> n % 2 == 0; 15 | List filteredNumbers = numbers.stream() 16 | .filter(evenNumber) 17 | .collect(Collectors.toList()); 18 | 19 | System.out.println(filteredNumbers); // 2, 4, 6, 8, 10 20 | System.out.println(evenNumber.test(4)); // true 21 | System.out.println(evenNumber.test(5)); // false 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/FilteringExampleApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.function.Predicate; 7 | 8 | public class FilteringExampleApp { 9 | 10 | public static void main(String[] args) { 11 | List words = Arrays.asList("green", "blue", "yellow", "red", "white"); 12 | 13 | List filteredWords = filter(words, s -> s.startsWith("b")); 14 | System.out.println(filteredWords); 15 | } 16 | 17 | public static List filter(List list, Predicate predicate) { 18 | List result = new ArrayList<>(); 19 | for (T t : list) { 20 | if (predicate.test(t)) { 21 | result.add(t); 22 | } 23 | } 24 | return result; 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/parameterization/CombinationExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.parameterization; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | import java.util.function.Predicate; 7 | import java.util.stream.Collectors; 8 | 9 | public class CombinationExample { 10 | 11 | public static void main(String[] args) { 12 | List words = Arrays.asList("green", "blue", "yellow", "red", "white"); 13 | 14 | Predicate startsWithB = s -> s.startsWith("b"); 15 | Function lengthMapper = String::length; 16 | 17 | List filteredWordLengths = words.stream() 18 | .filter(startsWithB) 19 | .map(lengthMapper) 20 | .collect(Collectors.toList()); 21 | System.out.println(filteredWordLengths); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/lambda/comparator/TshirtSorter.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.lambda.comparator; 2 | 3 | import net.harunote.java8.functional.predicate.Tshirt; 4 | 5 | import java.util.Arrays; 6 | import java.util.Comparator; 7 | 8 | public class TshirtSorter { 9 | public static void main(String[] args) { 10 | Tshirt[] tshirts = {new Tshirt(10000, "red"), new Tshirt(5000, "blue"), new Tshirt(8000, "green")}; 11 | 12 | // 익명 클래스를 이용한 정렬 13 | Comparator priceComparator = new Comparator() { 14 | @Override 15 | public int compare(Tshirt o1, Tshirt o2) { 16 | return o1.getPrice() - o2.getPrice(); 17 | } 18 | }; 19 | 20 | 21 | Arrays.sort(tshirts, priceComparator); 22 | 23 | for (Tshirt tshirt : tshirts) { 24 | System.out.println(tshirt); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/adapter/MediaAdapter.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.adapter; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 6 | */ 7 | public class MediaAdapter implements MediaPlayer { 8 | AdvancedMediaPlayer advancedMediaPlayer; 9 | 10 | public MediaAdapter(String audioType) { 11 | 12 | if (audioType.equalsIgnoreCase("vlc")) { 13 | advancedMediaPlayer = new VlcPlayer(); 14 | } else if (audioType.equalsIgnoreCase("mp4")) { 15 | advancedMediaPlayer = new Mp4Player(); 16 | } 17 | } 18 | 19 | 20 | 21 | @Override 22 | public void play(String audioType, String fileName) { 23 | if (audioType.equalsIgnoreCase("vlc")) { 24 | advancedMediaPlayer.playVlc(fileName); 25 | } else if (audioType.equalsIgnoreCase("mp4")) { 26 | advancedMediaPlayer.playMp4(fileName); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/facade/WithoutFacadeInterfaceApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.facade; 2 | 3 | import java.sql.Connection; 4 | 5 | /** 6 | * @author CodeVillains 7 | * @version 2022/12/28 8 | * @implNote Facade(표면, 외관, 창구) 패턴은 복잡한 하위 시스템에 대한 단순화된 상위 인터페이스를 제공한다. 9 | */ 10 | 11 | public class WithoutFacadeInterfaceApp { 12 | public static void main(String[] args) { 13 | String tableName="Company"; 14 | 15 | //generating MySql HTML report and Oracle PDF report without using Facade 16 | Connection con = MySqlHelper.getMySqlDBConnection(); 17 | MySqlHelper mySqlHelper = new MySqlHelper(); 18 | mySqlHelper.generateMySqlHTMLReport(tableName, con); 19 | 20 | Connection con1 = OracleHelper.getOracleDBConnection(); 21 | OracleHelper oracleHelper = new OracleHelper(); 22 | oracleHelper.generateOraclePDFReport(tableName, con1); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/ArraySort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArraySort { 6 | public static void main(String[] args) { 7 | 8 | String[] s = { "b", "A", "D", "C", "a", "F" }; 9 | 10 | // 대소문자 구분하여 정렬 11 | Arrays.sort(s); 12 | System.out.println("# 대소문자 구분"); 13 | System.out.println(Arrays.toString(s)); 14 | 15 | descArraySort(s); 16 | System.out.println("# 역정렬 "); 17 | System.out.println(Arrays.toString(s)); 18 | 19 | // 대소문자 구분 없이 정렬 20 | System.out.println("# 대소문자 구분없이 "); 21 | Arrays.sort(s, String.CASE_INSENSITIVE_ORDER); 22 | System.out.println(Arrays.toString(s)); 23 | 24 | } 25 | 26 | public static void descArraySort(String[] arr) { 27 | String temp; 28 | 29 | for (int i = 0; i < arr.length / 2; i++) { 30 | temp = arr[i]; 31 | arr[i] = arr[(arr.length - 1) - i]; 32 | arr[(arr.length - 1) - i] = temp; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/ArrayListToArrayDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 10 | */ 11 | class ArrayListToArrayDemo { 12 | 13 | public static void main(String args[]) { 14 | 15 | // 배열 리스트를 만든다. 16 | List al = new ArrayList<>(); 17 | // 배열 리스트에 요소를 추가한다. 18 | al.add(new Integer(1)); 19 | al.add(new Integer(2)); 20 | al.add(new Integer(3)); 21 | al.add(new Integer(4)); 22 | System.out.println("Contents of al: " + al); 23 | 24 | // 배열을 얻는다. 25 | Object ia[] = al.toArray(); 26 | int sum = 0; 27 | 28 | // 배열 요소들의 합계를 구한다. 29 | for (int i = 0; i < ia.length; i++) { 30 | sum += ((Integer) ia[i]).intValue(); 31 | } 32 | 33 | System.out.println("Sum is: " + sum); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/legacy/CarTest.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.legacy; 2 | 3 | /** 4 | * @author CodeVillains 5 | * @version 2022/12/20 6 | * @implNote 7 | */ 8 | public class CarTest { 9 | 10 | public static void main(String[] args) { 11 | CarTest carTest = new CarTest(); 12 | 13 | Car car = carTest.createCar("SEDAN"); 14 | 15 | System.out.println(car.toString()); 16 | } 17 | 18 | private Car createCar(String carName) { 19 | Car car; 20 | 21 | if (carName.equalsIgnoreCase(Car.SEDAN_CAR)) { 22 | car = new Car(Car.SEDAN_CAR); 23 | } else if (carName.equalsIgnoreCase(Car.SMALL_CAR)) { 24 | car = new Car(Car.SMALL_CAR); 25 | } else if (carName.equalsIgnoreCase(Car.LUXURY_CAR)) { 26 | car = new Car(Car.LUXURY_CAR); 27 | } else { 28 | car = new Car(""); 29 | } 30 | return car; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/BinaryGap.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | public class BinaryGap { 10 | 11 | public static void main(String[] args) throws UnsupportedEncodingException { 12 | int x = 2; 13 | 14 | // decimal to binary 15 | String binaryString = Integer.toBinaryString(x); 16 | 17 | // decimal to hexadecimal 18 | String hexString = Integer.toHexString(x); 19 | 20 | // ASCII Code to String 21 | String charAscII = Character.toString((char) x); 22 | 23 | System.out.println("binary : " + binaryString); 24 | System.out.println("hex : " + hexString); 25 | System.out.println("ASCII : " + charAscII); 26 | 27 | 28 | String str = "1226#24#"; 29 | 30 | int val = str.charAt(0) - '0'; 31 | System.out.println(val); 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/ArrayListDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 10 | */ 11 | class ArrayListDemo { 12 | public static void main(String args[]) { 13 | 14 | // 배열 리스트를 만든다. 15 | List al = new ArrayList<>(); 16 | System.out.println("Initial size of al: " + al.size()); 17 | 18 | // 배열 리스트에 요소들을 추가한다. 19 | al.add("C"); 20 | al.add("A"); 21 | al.add("E"); 22 | al.add("B"); 23 | al.add("D"); 24 | al.add("F"); 25 | al.add(1, "A2"); // index 1에 A2 값을 추가함 26 | System.out.println("Size of al after additions: " + al.size()); 27 | 28 | // 배열 리스트를 출력한다. 29 | System.out.println("Contents of al: " + al); 30 | 31 | // 배열 리스트에서 요소들을 삭제한다. 32 | al.remove("F"); 33 | al.remove(2); 34 | 35 | System.out.println("Size of al after deletions: " + al.size()); 36 | System.out.println("Contents of al: " + al); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/template/application/HouseTemplate.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.template.application; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | @Slf4j 8 | public abstract class HouseTemplate { 9 | 10 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 11 | 12 | //template method, final so subclasses can't override 13 | public final void buildHouse(){ 14 | buildFoundation(); // 건물 기초를 짓는다. 15 | buildPillars(); // 건물 기둥을 짓는다. 16 | buildWalls(); // 건물 벽을 짓는다. 17 | buildWindows(); // 건물 창호를 만든다. 18 | 19 | logger.info("집이 완공되었다."); 20 | } 21 | 22 | //default implementation 23 | private void buildWindows() { 24 | logger.info("창호가 완성 되었다."); 25 | } 26 | 27 | //methods to be implemented by subclasses 28 | public abstract void buildWalls(); 29 | public abstract void buildPillars(); 30 | 31 | private void buildFoundation() { 32 | logger.info("건물의 기초 공사가 시작 되었다."); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/facade/OracleHelper.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.facade; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.sql.Connection; 7 | 8 | 9 | public class OracleHelper { 10 | 11 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 12 | 13 | public static Connection getOracleDBConnection() { 14 | // get DB connection using connection parameters 15 | return null; 16 | } 17 | 18 | public void generateOraclePDFReport(String tableName, Connection con) { 19 | //get data from table and generate pdf report 20 | logger.info("오라클 DB의 테이블에서 PDF를 생성한다."); 21 | } 22 | 23 | public void generateOracleHTMLReport(String tableName, Connection con) { 24 | //get data from table and generate pdf report 25 | logger.info("오라클 DB의 테이블에서 HTML를 생성한다."); 26 | } 27 | 28 | public String generateOracleJsonReport(String tableName, Connection connection) { 29 | logger.info("오라클 DB의 테이블에서 JSON 데이터를 생성한다."); 30 | return null; 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/FindKim.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : findKim 함수(메소드)는 String형 배열 seoul을 매개변수로 받습니다. 8 | * seoul의 element중 "Kim"의 위치 x를 찾아, "김서방은 x에 있다"는 String을 반환하시오. 9 | * seoul에 "Kim"은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다. 10 | */ 11 | public class FindKim { 12 | public String findKim(String[] seoul){ 13 | //x에 김서방의 위치를 저장하시오. 14 | /* 15 | int x = 0; 16 | 17 | for (String str : seoul) { 18 | if ("Kim".equals(str)) { 19 | break; 20 | } 21 | x++; 22 | } 23 | */ 24 | final String find = "Kim"; 25 | int x = Arrays.asList(seoul).indexOf(find); 26 | 27 | return "김서방은 "+ x + "에 있다"; 28 | } 29 | 30 | // 실행을 위한 테스트코드입니다. 31 | public static void main(String[] args) { 32 | FindKim kim = new FindKim(); 33 | String[] names = {"Queen", "Tod","Kim"}; 34 | System.out.println(kim.findKim(names)); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/loadbalancer/RoundRobinLoadBalancer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.loadbalancer; 2 | 3 | import java.util.List; 4 | 5 | public class RoundRobinLoadBalancer { 6 | private List serverList; 7 | private int currentIndex = 0; 8 | 9 | public RoundRobinLoadBalancer(List serverList) { 10 | this.serverList = serverList; 11 | } 12 | 13 | public String getNextServer() { 14 | int index = currentIndex % serverList.size(); 15 | currentIndex++; 16 | return serverList.get(index); 17 | } 18 | 19 | public static void main(String[] args) { 20 | // 서버 목록 설정 21 | List serverList = List.of("1번 서버", "2번 서버", "3번 서버"); 22 | RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(serverList); 23 | 24 | // 10개의 요청을 처리할 서버 선택 25 | for (int i = 0; i < 10; i++) { 26 | String server = loadBalancer.getNextServer(); 27 | System.out.println("요청 " + (i + 1) + "번째 " + server + "로 진입"); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/ArraySort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArraySort { 6 | 7 | public static void main(String[] args) { 8 | 9 | String[] s = {"b", "A", "D", "C", "a", "F"}; 10 | 11 | // 대소문자 구분하여 정렬 12 | Arrays.sort(s); 13 | System.out.println("# 대소문자 구분"); 14 | System.out.println(Arrays.toString(s)); 15 | 16 | descArraySort(s); 17 | System.out.println("# 역정렬 "); 18 | System.out.println(Arrays.toString(s)); 19 | 20 | // 대소문자 구분 없이 정렬 21 | System.out.println("# 대소문자 구분없이 "); 22 | Arrays.sort(s, String.CASE_INSENSITIVE_ORDER); 23 | System.out.println(Arrays.toString(s)); 24 | 25 | } 26 | 27 | public static void descArraySort(String[] arr) { 28 | String temp; 29 | 30 | for (int i = 0; i < arr.length / 2; i++) { 31 | temp = arr[i]; 32 | arr[i] = arr[(arr.length - 1) - i]; 33 | arr[(arr.length - 1) - i] = temp; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/HashTableDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.Enumeration; 4 | import java.util.Hashtable; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 9 | */ 10 | public class HashTableDemo { 11 | 12 | public static void main(String args[]) { 13 | // Create a hash map 14 | Hashtable ht = new Hashtable(); 15 | Enumeration names; 16 | String str; 17 | 18 | ht.put("홍길동이", new Double(1240.34)); 19 | ht.put("김영순이", new Double(223.39)); 20 | ht.put("퀵군", new Double(1378.00)); 21 | ht.put("글라이더님", new Double(9999.55)); 22 | ht.put("존 도", new Double(-122.08)); 23 | ht.put("한효주님", new Double(55.77)); 24 | 25 | names = ht.keys(); 26 | while (names.hasMoreElements()) { 27 | str = (String) names.nextElement(); 28 | System.out.println(str + ": " + ht.get(str)); 29 | } 30 | System.out.println(); 31 | 32 | double bonus = ((Double) ht.get("존 도")).doubleValue(); 33 | ht.put("존 도", new Double(bonus + 1000)); 34 | System.out.println("존 도's new deposit: " + ht.get("존 도")); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/MapDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | 9 | /** 10 | * @Author : CodeVillains 11 | * @Description : 12 | */ 13 | public class MapDemo { 14 | 15 | public static void main(String[] args) { 16 | Map map = new HashMap(); 17 | 18 | // Key : 회원번호 , value : 이름 - map.put을 이용하여 데이터를 저장한다. 19 | map.put(1, "홍길동이"); 20 | map.put(2, "Samsig"); 21 | map.put(3, "Harunote"); 22 | map.put(100, "Kakao"); 23 | 24 | System.out.println(map); 25 | System.out.println(map.get(100)); 26 | 27 | // 값 찾기 (Key 혹은 Value) 존재하면 True 28 | System.out.println(map.containsKey(3)); 29 | System.out.println(map.containsValue("Samsig")); 30 | 31 | 32 | // 키를 Set에 담기, Key는 Integer 로 정의 되어있다. 33 | Set keys = map.keySet(); 34 | System.out.println(keys); 35 | 36 | 37 | // 값을 Collection에 담기, Value는 String으로 정의 되어있다. 38 | Collection values = map.values(); 39 | System.out.println(values); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/decorator/StarBuzzApps.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.decorator; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : 객체에 추가 요소를 동적으로 더할 수 있다. 상속을 통해 확장하면 유연성이 떨어진다 6 | */ 7 | public class StarBuzzApps { 8 | 9 | public static void main(String[] args) { 10 | Beverage beverage = new Espresso(); 11 | System.out.println("기본 에스프레소 = " + beverage.getDescription() + " : " + beverage.cost()); 12 | 13 | Beverage beverage1 = new DarkRoast(); 14 | 15 | beverage1 = new Mocha(beverage1); 16 | beverage1 = new Mocha(beverage1); 17 | beverage1 = new Whip(beverage1); 18 | 19 | System.out.println("다크로스트에 모카 추가, 휘핑 추가 = " + beverage1.getDescription() + " : " + beverage1.cost()); 20 | 21 | 22 | Beverage beverage2 = new HouseBlend(); 23 | 24 | beverage2 = new Mocha(beverage2); 25 | beverage2 = new Soy(beverage2); 26 | beverage2 = new Whip(beverage2); 27 | 28 | System.out.println("하우스에 모카 추가, 두유 추가, 휘핑 추가 = " + beverage2.getDescription() + " : " + beverage2.cost()); 29 | } 30 | 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/LinkedListDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.LinkedList; 4 | 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 9 | */ 10 | public class LinkedListDemo { 11 | 12 | public static void main(String args[]) { 13 | // 링크드 리스트를 생성. 14 | LinkedList ll = new LinkedList(); 15 | 16 | // 링크드 리스트에 요소를 추가한다. 17 | ll.add("F"); 18 | ll.add("B"); 19 | ll.add("D"); 20 | ll.add("E"); 21 | ll.add("C"); 22 | ll.addLast("Z"); 23 | ll.addFirst("A"); 24 | 25 | ll.add(1, "A2"); 26 | 27 | System.out.println("Original contents of ll: " + ll); 28 | 29 | // 링크드 리스트에서 요소를 삭제한다. 30 | ll.remove("F"); 31 | ll.remove(2); 32 | 33 | System.out.println("Contents of ll after deletion: " + ll); 34 | 35 | // 첫 번째와 마지막 요소를 삭제한다. 36 | ll.removeFirst(); 37 | ll.removeLast(); 38 | System.out.println("ll after deleting first and last: " + ll); 39 | 40 | // 값을 가져오고 값을 설정한다. 41 | Object val = ll.get(2); 42 | ll.set(2, (String) val + " Changed"); 43 | 44 | System.out.println("ll after change: " + ll); 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/TestMap.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | public class TestMap { 12 | 13 | private static final Logger logger = LoggerFactory.getLogger(TestMap.class); 14 | 15 | public static void main(String[] args) { 16 | Map addr = new HashMap(); 17 | addr.put("가가가1", "1"); 18 | addr.put("나나나2", "1"); 19 | addr.put("가가가1", "1"); 20 | addr.put("다다다0", "1"); 21 | 22 | logger.info("# Map 에 담긴 자료 : {}", addr); 23 | 24 | Set set = addr.keySet(); 25 | Object[] hmKeys = set.toArray(); 26 | Arrays.sort(hmKeys, nameSorter); // 이름순 정렬하기 27 | 28 | for (int i = 0; i < hmKeys.length; i++) { 29 | String key = (String) hmKeys[i]; 30 | logger.info("# key = {}", key); 31 | } 32 | } 33 | 34 | public static Comparator nameSorter = (s1, s2) -> { 35 | String ss1 = (String) s1; 36 | String ss2 = (String) s2; 37 | return (-1) * ss2.compareTo(ss1); 38 | }; 39 | 40 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/facade/HelperFacade.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.facade; 2 | 3 | import java.sql.Connection; 4 | 5 | public class HelperFacade { 6 | 7 | public static void generateReport(DBTypes dbType, ReportTypes reportType, String tableName){ 8 | Connection con = null; 9 | switch (dbType){ 10 | case MYSQL: 11 | con = MySqlHelper.getMySqlDBConnection(); 12 | MySqlHelper mySqlHelper = new MySqlHelper(); 13 | switch(reportType){ 14 | case HTML: 15 | mySqlHelper.generateMySqlHTMLReport(tableName, con); 16 | break; 17 | case PDF: 18 | mySqlHelper.generateMySqlPDFReport(tableName, con); 19 | break; 20 | } 21 | break; 22 | case ORACLE: 23 | con = OracleHelper.getOracleDBConnection(); 24 | OracleHelper oracleHelper = new OracleHelper(); 25 | switch(reportType){ 26 | case HTML: 27 | oracleHelper.generateOracleHTMLReport(tableName, con); 28 | break; 29 | case PDF: 30 | oracleHelper.generateOraclePDFReport(tableName, con); 31 | break; 32 | } 33 | break; 34 | } 35 | 36 | } 37 | 38 | public enum DBTypes{ 39 | MYSQL,ORACLE; 40 | } 41 | 42 | public enum ReportTypes{ 43 | HTML,PDF; 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/pattern/factory/pizzastore/Pizza.java: -------------------------------------------------------------------------------- 1 | package net.harunote.pattern.factory.pizzastore; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 팩토리 패턴 - 객체 생성하는 부분을 서브 클래스에게 위임 8 | */ 9 | public abstract class Pizza { 10 | String name; 11 | String dough; 12 | String sauce; 13 | ArrayList toppings = new ArrayList(); 14 | 15 | void prepare() { 16 | System.out.println("Preparing " + name); 17 | System.out.println("Tossing dough... " ); 18 | System.out.println("adding sauce... " ); 19 | System.out.println("adding toppings... " ); 20 | 21 | for (int i = 0; i < toppings.size(); i++) { 22 | System.out.println(" " + toppings.get(i)); 23 | } 24 | } 25 | 26 | void bake() { 27 | System.out.println("Bake for 25 minutes at 350"); 28 | } 29 | 30 | void cut() { 31 | System.out.println("Cutting the pizza into diagonal slices"); 32 | } 33 | 34 | void box() { 35 | System.out.println("Place pizza in official PizzaStore box"); 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/WaterMelon.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @Author : CodeVillains 5 | * @Description : water_melon함수는 정수 n을 매개변수로 입력받습니다. 6 | * 길이가 n이고, 수박수박수...와 같은 패턴을 유지하는 문자열을 리턴하도록 함수를 완성하시오. 7 | * 예를들어 n이 4이면 '수박수박'을 리턴하고 3이라면 '수박수'를 리턴하면 됩니다. 8 | */ 9 | public class WaterMelon { 10 | public String waterMelon(int n){ 11 | /* 12 | String result = ""; 13 | for (int i = 1; i <= n; i++) { 14 | // 홀수면 수 15 | if (i % 2 == 1) { 16 | result +="수"; 17 | } else { 18 | result +="박"; 19 | } 20 | // 짝수면 박 21 | } 22 | return result; 23 | */ 24 | 25 | StringBuffer stringBuffer = new StringBuffer(); 26 | 27 | for (int i = 1; i <= n; i++) { 28 | stringBuffer.append(i % 2 == 1 ? "수" : "박"); 29 | } 30 | 31 | return stringBuffer.toString(); 32 | } 33 | 34 | // 실행을 위한 테스트코드입니다. 35 | public static void main(String[] args){ 36 | WaterMelon wm = new WaterMelon(); 37 | System.out.println("n이 3인 경우: " + wm.waterMelon(3)); 38 | System.out.println("n이 4인 경우: " + wm.waterMelon(4)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 삽입 정렬, 배열의 모든 요소를 앞에서부터 차례대로 이미 정렬된 배열 부분과 비교하여, 자신의 위치를 찾아 삽입함. 대상을 기준값의 왼쪽 요소부터 8 | * 비교해서 기준값의 크기가 비교값보다 작을 경우 두개의 위치를 바꿔주고 기준값을 저장한다. (반복하면서 정렬) performance : O(n^2) 9 | */ 10 | public class InsertionSort { 11 | 12 | public static void main(String[] args) { 13 | int[] numbers = {9, 10, 2, 6, 8}; 14 | 15 | for (int i = 1; i < numbers.length; i++) { 16 | int standard = numbers[i]; // 기준값 (제일 처음 비교시 1번째 방이 기준점으로 왼쪽을 비교, 최초값은 10 17 | 18 | int compare = i - 1; // 비교대상 (기준값의 왼쪽 요소를 비교), 최초값은 0 19 | 20 | // 비교대상이 0보다 크고 기준값이 비교 대상보다 작을 경우 swap 21 | while (compare >= 0 && standard < numbers[compare]) { // 0 >= 0 && 10 < 9 22 | numbers[compare + 1] = numbers[compare]; // 비교 대상을 오른쪽으로 밀어냄 23 | compare--; // -1이 되면 조건밖으로 이동 24 | } 25 | 26 | numbers[compare + 1] = standard; // 기준값을 저장한다. 최초에는 조건이 맞지 않으므로 정렬하지 못함 27 | } 28 | 29 | System.out.print("result = "); 30 | System.out.println(Arrays.toString(numbers)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/structure/PriorityQueueExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.structure; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 우선 순위 큐 8 | */ 9 | public class PriorityQueueExample { 10 | public static void main(String[] args) { 11 | PriorityQueue priorityQueue = new PriorityQueue<>(); 12 | // enqueue 13 | priorityQueue.add(3); 14 | priorityQueue.add(1); 15 | priorityQueue.add(2); 16 | // dequeue 17 | int element = priorityQueue.poll(); 18 | 19 | System.out.println(element); // 출력: 1 (우선순위가 가장 높은 값이 먼저 꺼내짐) 20 | priorityQueue.peek(); 21 | printQueue(priorityQueue); 22 | 23 | priorityQueue.add(5); 24 | priorityQueue.add(4); 25 | priorityQueue.add(3); 26 | 27 | if (!priorityQueue.isEmpty()) { 28 | System.out.println(priorityQueue.poll()); 29 | printQueue(priorityQueue); 30 | } 31 | } 32 | 33 | private static void printQueue(PriorityQueue priorityQueue) { 34 | while (!priorityQueue.isEmpty()) { 35 | System.out.println("priorityQueue : " + priorityQueue.poll()); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/HashMapDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | 9 | /** 10 | * @Author : CodeVillains 11 | * @Description : 12 | */ 13 | public class HashMapDemo { 14 | 15 | public static void main(String args[]) { 16 | // 해시 맵을 만든다. 17 | Map hm = new HashMap(); 18 | // 맵에 요소들을 넣는다. 19 | hm.put("홍길동이", new Double(1240.34)); 20 | hm.put("김영순이", new Double(223.39)); 21 | hm.put("퀵군", new Double(1378.00)); 22 | hm.put("글라이더님", new Double(9999.55)); 23 | hm.put("존 도", new Double(-122.08)); 24 | hm.put("한효주님", null); 25 | 26 | // 맵 엔트리의 콜렉션 집합을 가져온다. 27 | Set set = hm.entrySet(); 28 | 29 | // 반복자를 얻는다. 30 | Iterator i = set.iterator(); 31 | 32 | // 요소들을 출력한다. 33 | while(i.hasNext()) { 34 | Map.Entry me = (Map.Entry)i.next(); 35 | System.out.print(me.getKey() + ": "); 36 | System.out.println(me.getValue()); 37 | } 38 | 39 | // 존 도의 계좌에 1000을 예금한다. 40 | double bonus = hm.get("존 도").doubleValue(); 41 | hm.put("존 도", new Double(bonus + 1000)); 42 | System.out.println("존 도's new deposit: " + hm.get("존 도")); 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/TreeMapDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.Iterator; 4 | import java.util.Map; 5 | import java.util.Set; 6 | import java.util.TreeMap; 7 | 8 | 9 | /** 10 | * @Author : CodeVillains 11 | * @Description : 12 | */ 13 | public class TreeMapDemo { 14 | 15 | public static void main(String args[]) { 16 | // 해시 맵을 만든다. 17 | Map tm = new TreeMap(); 18 | // 맵에 요소들을 넣는다. 19 | tm.put("홍길동이", new Double(1240.34)); 20 | tm.put("김영순이", new Double(223.39)); 21 | tm.put("퀵군", new Double(1378.00)); 22 | tm.put("글라이더님", new Double(9999.55)); 23 | tm.put("존 도", new Double(-122.08)); 24 | tm.put("한효주님", null); 25 | 26 | // 맵 엔트리의 콜렉션 집합을 가져온다. 27 | Set set = tm.entrySet(); 28 | 29 | // 반복자를 얻는다. 30 | Iterator i = set.iterator(); 31 | 32 | // 요소들을 출력한다. 33 | while(i.hasNext()) { 34 | Map.Entry me = (Map.Entry)i.next(); 35 | System.out.print(me.getKey() + ": "); 36 | System.out.println(me.getValue()); 37 | } 38 | 39 | // 존 도의 계좌에 1000을 예금한다. 40 | double bonus = tm.get("존 도").doubleValue(); 41 | tm.put("존 도", new Double(bonus + 1000)); 42 | System.out.println("존 도's new deposit: " + tm.get("존 도")); 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/AlgorithmsDemo.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | public class AlgorithmsDemo { 10 | 11 | public static void main(String args[]) { 12 | 13 | // 링크드 리스트를 만들고 초기화한다. 14 | LinkedList ll = new LinkedList(); 15 | ll.add(new Integer(-8)); 16 | ll.add(new Integer(20)); 17 | ll.add(new Integer(-20)); 18 | ll.add(new Integer(8)); 19 | 20 | // 역순의 비교자를 생성. 21 | Comparator r = Collections.reverseOrder(); 22 | 23 | // 비교자를 사용해서 리스트를 정렬한다. 24 | Collections.sort(ll, r); 25 | 26 | // 반복자를 얻는다. 27 | Iterator li = ll.iterator(); 28 | 29 | System.out.print("List sorted in reverse: "); 30 | while (li.hasNext()) { 31 | System.out.print(li.next() + " "); 32 | } 33 | 34 | System.out.println(); 35 | 36 | Collections.shuffle(ll); 37 | 38 | // 임의의 리스트를 표시한다. 39 | li = ll.iterator(); 40 | System.out.print("List shuffled: "); 41 | 42 | while (li.hasNext()) { 43 | System.out.print(li.next() + " "); 44 | } 45 | System.out.println(); 46 | 47 | System.out.println("Minimum: " + Collections.min(ll)); 48 | System.out.println("Maximum: " + Collections.max(ll)); 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 구성 요소를 순회하면서 인접한 요소간의 값을 비교하여 정렬. 뒤에 값이 작으면 앞으로 위치를 바꿔줘야 하기 때문에 가변 공간이 하나 필요하다. 8 | * Performance : 비효율적이다. 최악의 경우 역순으로 정렬하려고 할 때 O(n^2)가 나오고 최선은 리스트가 이미 정렬이 되어있을 경우 O(N)의 성능이 나온다. 9 | */ 10 | public class BubbleSort { 11 | 12 | public static void main(String[] args) { 13 | final int[] numbers = {4, 7, 1, 2, 5, 8, 6}; 14 | 15 | System.out.println("Result = " + Arrays.toString(bubbleSort(numbers))); 16 | } 17 | 18 | private static int[] bubbleSort(int[] numbers) { 19 | boolean switched; 20 | do { 21 | switched = false; 22 | for (int i = 0; i < numbers.length - 1; i++) { 23 | // 첫번째 원소와 현재 원소를 비교해서 현재 원소보다 작으면 swap 24 | if (numbers[i + 1] < numbers[i]) { // 뒤에 값이 현재 값보다 작을 경우 위치를 바꿔준다. 25 | int temp = numbers[i + 1]; // 기준값을 위한 임시 공간이 필요 26 | numbers[i + 1] = numbers[i]; 27 | numbers[i] = temp; 28 | switched = true; 29 | } 30 | } 31 | 32 | } while (switched); 33 | return numbers; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/calculation/Average.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.calculation; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 주어진 파라미터의 평균값 구하는 알고리즘 8 | */ 9 | public class Average { 10 | public static void main(String[] args) { 11 | // Scanner scan = new Scanner(System.in); 12 | int[] params = {2, 3, 6, 8}; 13 | 14 | Average average = new Average(); 15 | System.out.println("평균값 : " + average.calAverage(params)); 16 | } 17 | 18 | public int calAverage(int[] params) { 19 | // basic type 20 | /* 21 | int sum = 0; 22 | int totalSize = params.length; 23 | if (totalSize < 1) { 24 | return 0; 25 | } 26 | 27 | for (int i = 0; i < totalSize; i++) { 28 | sum += params[i]; 29 | } 30 | 31 | return Math.round(sum / totalSize); 32 | */ 33 | 34 | /* 35 | int sum = 0; 36 | if (params == null) { 37 | return 0; 38 | } 39 | 40 | for (int n : params) { 41 | sum += n; 42 | } 43 | 44 | return sum / params.length; 45 | */ 46 | 47 | // Lambda 48 | return (int) Arrays.stream(params).average().orElse(0); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/LibraryFine.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | 10 | public class LibraryFine { 11 | final Integer YEAR_FEE = 10000; 12 | final Integer MONTH_FEE = 500; 13 | final Integer DAY_FEE = 15; 14 | 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | int d1 = in.nextInt(); 18 | int m1 = in.nextInt(); 19 | int y1 = in.nextInt(); 20 | int d2 = in.nextInt(); 21 | int m2 = in.nextInt(); 22 | int y2 = in.nextInt(); 23 | 24 | // 연도를 비교한다. 25 | LibraryFine sul = new LibraryFine(); 26 | int result = sul.calcDate(d1, m1, y1, d2, m2, y2); 27 | System.out.println(result); 28 | } 29 | 30 | public int calcDate(int d1, int m1, int y1, int d2, int m2, int y2) { 31 | int mon = 0; 32 | int day = 0; 33 | 34 | if (y1 > y2) { 35 | return YEAR_FEE; 36 | } 37 | 38 | if (m1 > m2) { 39 | mon = (m1 - m2) * MONTH_FEE; 40 | } 41 | 42 | if (d1 > d2) { 43 | day = (d1 - d2) * DAY_FEE; 44 | } 45 | 46 | return mon + day; 47 | 48 | } 49 | 50 | 51 | } 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/java8/functional/predicate/TshirtPredicateApp.java: -------------------------------------------------------------------------------- 1 | package net.harunote.java8.functional.predicate; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | import static java.util.Arrays.asList; 8 | 9 | /** 10 | * @author CodeVillains 11 | */ 12 | public class TshirtPredicateApp { 13 | public static void main(String[] args) { 14 | List myShirtList = asList(new Tshirt(100, "yellow"), 15 | new Tshirt(200, "green"), 16 | new Tshirt(300, "blue"), 17 | new Tshirt(400, "red"), 18 | new Tshirt(500, "white")); 19 | 20 | List priceFilter = filter(myShirtList, new TshirtPricePredicate()); 21 | List colorFilter = filter(myShirtList, new TshirtColorPredicate()); 22 | 23 | System.out.println("price filter = " + priceFilter); 24 | System.out.println("color filter = " + colorFilter); 25 | } 26 | 27 | private static List filter(List myShirtList, TshirtPredicate predicate) { 28 | List list = new ArrayList<>(); 29 | for (Tshirt tshirt : myShirtList) { 30 | if (predicate.test(tshirt)) { 31 | list.add(tshirt); 32 | } 33 | } 34 | return list; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/CurrentBuffer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | /** 4 | * @Description : 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class CurrentBuffer { 10 | final Integer YEAR_FEE = 10000; 11 | final Integer MONTH_FEE = 500; 12 | final Integer DAY_FEE = 15; 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | int d1 = in.nextInt(); 17 | int m1 = in.nextInt(); 18 | int y1 = in.nextInt(); 19 | int d2 = in.nextInt(); 20 | int m2 = in.nextInt(); 21 | int y2 = in.nextInt(); 22 | 23 | // 연도를 비교한다. 24 | CurrentBuffer sul = new CurrentBuffer(); 25 | int result = sul.calcDate(d1, m1, y1, d2, m2, y2); 26 | System.out.println(result); 27 | } 28 | 29 | public int calcDate(int d1, int m1, int y1, int d2, int m2, int y2) { 30 | int result = 0; 31 | 32 | if (y1 < y2) { 33 | return 0; 34 | } 35 | if (y1 > y2) { 36 | return YEAR_FEE; 37 | } 38 | 39 | if (m1 > m2) { 40 | result = (m1-m2) * MONTH_FEE; 41 | } else { 42 | result = 0; 43 | 44 | if (d1 > d2 && m1 >= m2) { 45 | result = (d1-d2) * DAY_FEE; 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/EncodedString.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | public class EncodedString { 10 | public static void main(String[] args) { 11 | 12 | String s = "23#(2)24#25#26#23#(3)"; 13 | 14 | int[] result = frequency(s); 15 | 16 | System.out.println(Arrays.toString(result)); 17 | } 18 | 19 | private static int[] frequency(String s) { 20 | int[] result = new int[26]; 21 | 22 | int size = s.length(); 23 | 24 | int i = 0; 25 | while (i < size) { 26 | int val = 0; 27 | 28 | if (i + 2 >= size || s.charAt(i + 2) != '#') { 29 | val = s.charAt(i) - '0'; 30 | result[val - 1]++; 31 | i++; 32 | } else if (s.charAt(i + 2) == '#') { 33 | val = (s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0'); 34 | result[val - 1]++; 35 | i = i + 3; 36 | } 37 | 38 | if (i < size) { 39 | if (s.charAt(i) == '(') { 40 | int frequen = s.charAt(i + 1) - '0'; 41 | result[val - 1] += frequen - 1; 42 | i = i + 3; 43 | } 44 | } 45 | } 46 | 47 | 48 | return result; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/TimeConversion.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : AM, PM으로 입력 받은 시간을 24시간 포맷으로 변경하라. 8 | * main 메소드에서 07:05:45PM 와 같은 값을 받았을 때 19:05:45 으로 시간 포맷을 변경하여 출력하라. 9 | */ 10 | public class TimeConversion { 11 | 12 | static String timeConversion(String s) { 13 | // Complete this function 14 | String format = s.substring(s.length() - 2, s.length()); 15 | System.out.println(format); 16 | 17 | if (format.equalsIgnoreCase("pm")) { 18 | int time = Integer.parseInt(s.substring(0, 2)); 19 | if (s.substring(0, 2).equals("12")) { 20 | return "12"+ s.substring(2, s.length()-2); 21 | } else { 22 | return time + 12 + s.substring(2, s.length()-2); 23 | } 24 | } else { 25 | if (s.substring(0, 2).equals("12")) { 26 | return "00"+ s.substring(2, s.length()-2); 27 | } else { 28 | return s.substring(0, s.length() - 2); 29 | } 30 | 31 | } 32 | 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | // 07:05:45PM -> 19:05:45 38 | Scanner in = new Scanner(System.in); 39 | String s = in.next(); 40 | String result = timeConversion(s); 41 | System.out.println(result); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 구현하기 쉬움 주어진 리스트에서 최소값을 찾아 맨 앞에 위치값과 비교하여 교체한다. 목록의 각 위치에 대해서 이러한 과정을 계속한다. 8 | * Performance : O(n^2) 9 | */ 10 | public class SelectionSort { 11 | 12 | public static void main(String[] args) { 13 | final int[] numbers = {11, 2, 6, 3, 9, 8}; 14 | 15 | System.out.println("Result = " + Arrays.toString(selectSort(numbers))); 16 | 17 | } 18 | 19 | private static int[] selectSort(int[] numbers) { 20 | 21 | // 전체 요소를 순회 한다. 마지막 공간은 자동으로 위치 교환을 통해 정렬된다. 22 | for (int index = 0; index < numbers.length - 1; index++) { 23 | int min = index; 24 | 25 | // 다음 요소를 현재요소와 비교한다. 다음요소가 현재의 요소바다 작을 경우 요소의 인덱스를 바꿔준다. 26 | for (int scan = index + 1; scan < numbers.length; scan++) { 27 | if (numbers[scan] < numbers[min]) { // 2 가 11보다 작으니 28 | min = scan; // 작은 인덱스를 min에 할당 0 = 1; 29 | } 30 | } 31 | 32 | int smaller = numbers[min]; // 1번째 공간값인 2가 가장 작은값이므로 smaller 에 저장 33 | numbers[min] = numbers[index]; // 1번째 공간에 0번째 값을 할당 34 | numbers[index] = smaller; // 0번째 공간에 가장 작은값을 할당 35 | 36 | } 37 | 38 | return numbers; 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/BirthdayCakeCandle.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @Author : CodeVillains 10 | * @Description : 입력값에서 중복된 값을 카운트 한다. 11 | */ 12 | public class BirthdayCakeCandle { 13 | 14 | static int birthdayCakeCandles(int n, int[] ar) { 15 | // Complete this function 16 | 17 | Map map = new HashMap<>(); 18 | 19 | // 목록을 돌면서 키가 존재할 경우 +1, 아니면 1을 value 에 저장한다. 20 | for (int i = 0; i < ar.length; i++) { 21 | if (map.containsKey(ar[i])) { 22 | map.put(ar[i], map.get(ar[i]) + 1); 23 | } else { 24 | map.put(ar[i], 1); 25 | } 26 | } 27 | 28 | map.forEach((k, v) -> System.out.println("Item : " + k + " Count : " + v)); 29 | 30 | // map 의 value 중 최대값을 추출 31 | int max = (Collections.max(map.values())); 32 | return max; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | 38 | // 4 39 | // 3 2 1 3 40 | 41 | int n = in.nextInt(); 42 | int[] ar = new int[n]; 43 | for (int ar_i = 0; ar_i < n; ar_i++) { 44 | ar[ar_i] = in.nextInt(); 45 | } 46 | int result = birthdayCakeCandles(n, ar); 47 | System.out.println(result); 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/CheckBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | /** 4 | * @Description : Given the root node of a binary tree, can you determine if it's also a binary search tree? 5 | * Complete the function in your editor below, which has parameter: a pointer to the root of a binary tree. 6 | * It must return a boolean denoting whether or not the binary tree is a binary search tree. 7 | * You may have to write one or more helper functions to complete this challenge. 8 | * 9 | * link : https://www.hackerrank.com/challenges/ctci-is-binary-search-tree?h_r=next-challenge&h_v=zen 10 | */ 11 | 12 | class Node { 13 | int data; 14 | Node left; 15 | Node right; 16 | } 17 | 18 | public class CheckBinarySearchTree { 19 | 20 | boolean checkBST(Node root) { 21 | boolean leftResult = false; 22 | boolean rightResult = false; 23 | if (root.left != null) { 24 | leftResult = checkLeft(root); 25 | } 26 | 27 | if (root.right != null) { 28 | rightResult = checkRight(root); 29 | } 30 | 31 | return leftResult && rightResult; 32 | } 33 | 34 | boolean checkLeft(Node root) { 35 | if (root.data > root.left.data) { 36 | return true; 37 | } else { 38 | return false; 39 | } 40 | } 41 | 42 | 43 | boolean checkRight(Node root) { 44 | if (root.data < root.right.data) { 45 | return true; 46 | } else { 47 | return false; 48 | } 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/arrays/MultiDimensional.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 9 | */ 10 | public class MultiDimensional { 11 | public static void main(String[] args) { 12 | int[] a = new int[3]; // 배열의 선언 13 | 14 | a[0] = 1; 15 | a[1] = 2; 16 | a[2] = 3; 17 | 18 | System.out.println(a.length); // 배열의 길이 19 | 20 | int[] b = {5, 2, 3, 1, 6, 8}; // 선언과 할당 21 | 22 | Arrays.sort(b); // 오름차순 정렬 23 | 24 | System.out.println(Arrays.toString(b)); 25 | 26 | Integer[] bInteger = new Integer[b.length]; 27 | for (int i = 0; i < b.length; i++) { 28 | bInteger[i] = b[i]; 29 | } 30 | 31 | Collections.reverse(Arrays.asList(bInteger)); // 내림차순 정렬 32 | 33 | System.out.println("# 내림 차순 정렬"); 34 | for (Integer in : bInteger) { 35 | System.out.print(in + ", "); 36 | } 37 | 38 | 39 | System.out.println("\n# 오름 차순 정렬"); 40 | Arrays.sort(bInteger); 41 | System.out.println(Arrays.toString(bInteger)); 42 | 43 | // 다 차원 배열 44 | int[][] table = { {1,2,3,4,5,6,7,8,9,10}, 45 | {2,3,4,5,6,7,8,9,10,1}, 46 | {3,4,5,6,7,8,9,10,1,2}, 47 | {4,5,6,7,8,9,10,1,2,3}, 48 | {5,6,7,8,9,10,1,2,3,4} }; 49 | 50 | System.out.println(table.length); 51 | System.out.println(table[0].length); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/CompareTheTriplets.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | /** 4 | * 5 | * @Description : 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class CompareTheTriplets { 11 | 12 | static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2) { 13 | // Complete this function 14 | int[] result = new int[2]; 15 | int alice = 0; 16 | int bob = 0; 17 | 18 | if (a0 > b0) { 19 | ++alice; 20 | } else { 21 | if (a0 < b0) { 22 | ++bob; 23 | } 24 | } 25 | 26 | if (a1 > b1) { 27 | ++alice; 28 | } else { 29 | if (a1 < b1) { 30 | ++bob; 31 | } 32 | } 33 | 34 | if (a2 > b2) { 35 | ++alice; 36 | } else { 37 | if (a2 < b2) { 38 | ++bob; 39 | } 40 | } 41 | result[0] = alice; 42 | result[1] = bob; 43 | return result; 44 | } 45 | 46 | public static void main(String[] args) { 47 | Scanner in = new Scanner(System.in); 48 | int a0 = in.nextInt(); 49 | int a1 = in.nextInt(); 50 | int a2 = in.nextInt(); 51 | int b0 = in.nextInt(); 52 | int b1 = in.nextInt(); 53 | int b2 = in.nextInt(); 54 | int[] result = solve(a0, a1, a2, b0, b1, b2); 55 | for (int i = 0; i < result.length; i++) { 56 | System.out.print(result[i] + (i != result.length - 1 ? " " : "")); 57 | } 58 | System.out.println(""); 59 | 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/MakingAnagrams.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 주어진 두개의 문자열이 anagram이 될 수 있도록 문자를 제거함 10 | * We delete the following characters from our two strings to turn them into anagrams of each other: 11 | * Remove d and e from cde to get c. 12 | * Remove a and b from abc to get c. 13 | * We must delete characters to make both strings anagrams, so we print on a new line. 14 | */ 15 | public class MakingAnagrams { 16 | public static int numberNeeded(String first, String second) { 17 | char[] one = first.toCharArray(); 18 | char[] two = second.toCharArray(); 19 | 20 | Map letter = new HashMap<>(); 21 | int count; 22 | 23 | for (char c : one) { 24 | count = letter.containsKey(c) ? letter.get(c) : 0; 25 | letter.put(c, count + 1); 26 | } 27 | 28 | for (char c : two) { 29 | count = letter.containsKey(c) ? letter.get(c) : 0; 30 | letter.put(c, count - 1); 31 | } 32 | 33 | int result = 0; 34 | for (char c : letter.keySet()) { 35 | result += Math.abs(letter.get(c)); 36 | } 37 | 38 | return result; 39 | } 40 | 41 | public static void main(String[] args) { 42 | // cde 43 | // abc 44 | Scanner in = new Scanner(System.in); 45 | String a = in.next(); 46 | String b = in.next(); 47 | System.out.println(numberNeeded(a, b)); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/arrays/LeftLotation.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 좌측 쉬프트 값이 주어질 때 Array의 위치를 변경해준다. 9 | * 예 [1,2,3,4,5] 를 2만큼 이동 시키면 [3,4,5,1,2] 가 되어야 한다. 10 | * 11 | */ 12 | public class LeftLotation { 13 | 14 | public static int[] arrayLeftRotation(int[] a, int n, int k) { // array, array 사이즈, 쉬프트 갯수 15 | //System.out.println("# n = " + n); 16 | //System.out.println("# k = " + k); 17 | int start = 0; 18 | 19 | while (start < k) { // k 만큼 돌면서 위치를 바꿔준다. 20 | int std = a[0]; 21 | for (int i = 0; i < a.length -1 ; i++) { 22 | a[i] = a[i + 1]; 23 | } 24 | 25 | a[a.length - 1] = std; 26 | 27 | start++; 28 | } 29 | 30 | System.out.println("result = " + Arrays.toString(a)); 31 | return a; 32 | } 33 | 34 | // 5 4 35 | // 1 2 3 4 5 36 | 37 | public static void main(String[] args) { 38 | Scanner in = new Scanner(System.in); 39 | int n = in.nextInt(); // 5 (1,2,3,4,5) 40 | int k = in.nextInt(); // 4 41 | int a[] = new int[n]; 42 | for(int a_i=0; a_i < n; a_i++){ 43 | a[a_i] = in.nextInt(); 44 | System.out.println("a_i = " + a[a_i]); 45 | } 46 | 47 | int[] output = new int[n]; 48 | output = arrayLeftRotation(a, n, k); 49 | for(int i = 0; i < n; i++) 50 | System.out.print(output[i] + " "); 51 | 52 | System.out.println(); 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/lru/LRUCache.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.lru; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 가장 오랫동안 사용되지 않은 엔트리(호출되지 않는)를 메모리의 후방에 위치하게 하여 메모리에서 삭제 하는 캐싱 알고리즘 LRU (최근사용우선) 와 9 | * 비슷한 알고리즘으로 LFU(Least Frequently Used : 참조 횟수 기준) 이 있다. 10 | */ 11 | 12 | public class LRUCache extends LinkedHashMap { 13 | private int cacheSize; 14 | 15 | // cacheSize는 생성할때 map의 크기를 얼마로 할 것인가가? loadFactor는 capacity의 몇 %가 차게되면 용량을 늘려야 할것인가 16 | // 마지막 불리언 값은 정렬을 삽입 순서(false)냐 접근 순서(true)냐에 대한 인자이다 17 | public LRUCache(int cacheSize) { 18 | super(cacheSize, 0.75f, true); 19 | this.cacheSize = cacheSize; 20 | } 21 | 22 | // 현재 맵의 크기보다 크면 true 리턴하고 first 노드를 찾아서 삭제함. 23 | @Override 24 | protected boolean removeEldestEntry(Map.Entry eldest) { 25 | return size() > cacheSize; 26 | } 27 | 28 | public static void main(String[] args) { 29 | LRUCache cache = new LRUCache<>(3); // LRU 캐시 크기를 3으로 설정 30 | 31 | cache.put(1, "첫번째 항목"); 32 | System.out.println(cache); 33 | 34 | cache.put(2, "두번째 항목"); 35 | System.out.println(cache); 36 | cache.put(3, "세번째 항목"); 37 | 38 | System.out.println(cache); // 출력: {1=첫번째 항목, 2=두번째 항목, 3=세번째 항목} 39 | 40 | cache.get(2); // 요소 2에 액세스하여 가장 최근 사용 위치로 이동 변경 41 | 42 | System.out.println(cache); // 출력: {1=첫번째 항목, 3=세번째 항목, 2=두번째 항목} 43 | 44 | cache.put(4, "네번째 항목"); // 용량 초과로 인해 LRU 항목의 first 노드 제거 45 | 46 | System.out.println(cache); // 출력: {1=첫번째 항목, 3=세번째 항목, 2=두번째 항목} 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/Palindrom.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | /** 4 | * @Author CodeVillains 5 | * 회문(palindrome)은 앞뒤로 읽어도 같은 단어입니다. 6 | * 주어진 단어가 회문인지 확인하는 함수를 작성하십시오. 대소문자는 무시해야 합니다. 7 | * 예를 들어 isPalindrome("Level")는 대소문자를 무시해야 하므로 true를 반환해야 합니다. 8 | */ 9 | public class Palindrom { 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Palindrom : " + Palindrom.isPalindrome("Level")); 13 | } 14 | 15 | private static boolean isPalindrome(String word) { 16 | if (word == null) { 17 | throw new UnsupportedOperationException("테스트 할 문자가 없습니다."); 18 | } 19 | String result = ""; 20 | for (int i = word.length() - 1; i >= 0; i--) { 21 | char charword = word.charAt(i); 22 | result += charword; 23 | } 24 | System.out.println("result : " + result); 25 | if (result.equalsIgnoreCase(word)) { 26 | return true; 27 | } else { 28 | return false; 29 | } 30 | } 31 | 32 | private static boolean isPalindrome2(String word) { 33 | if (word == null) { 34 | throw new UnsupportedOperationException("테스트 할 문자가 없습니다."); 35 | } 36 | 37 | int left = 0; 38 | int right = word.length() - 1; 39 | 40 | while (left < right) { 41 | char leftChar = Character.toLowerCase(word.charAt(left)); 42 | char rightChar = Character.toLowerCase(word.charAt(right)); 43 | 44 | if (leftChar != rightChar) { 45 | return false; 46 | } 47 | 48 | left++; 49 | right--; 50 | } 51 | 52 | return true; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/MinimumMoves.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | public class MinimumMoves { 10 | 11 | public static void main(String[] args) throws IOException { 12 | int[] a = {1234, 4321}; 13 | int[] b = {2345, 3214}; 14 | 15 | int count = minimumMoves(a, b); 16 | 17 | System.out.println("count : " + count); 18 | 19 | } 20 | 21 | static int minimumMoves(int[] a, int[] m) { 22 | 23 | int size = a.length; 24 | int result = 0; 25 | 26 | for (int i = 0; i < size; i++) { 27 | String first = a[i] + ""; 28 | String second = m[i] + ""; 29 | 30 | System.out.println("first : " + first); // 1234 31 | System.out.println("second : " + second); // 2345 32 | 33 | char[] ins = first.toCharArray(); 34 | char[] rst = second.toCharArray(); 35 | 36 | int value = counting(ins, rst); 37 | result += value; 38 | } 39 | 40 | return result; 41 | } 42 | 43 | static int counting(char[] ins, char[] rst) { 44 | 45 | int count = 0; 46 | for (int idx = 0; idx < ins.length; idx++) { 47 | if (ins[idx] > rst[idx]) { 48 | count += calc(ins[idx], rst[idx]); 49 | } else if (ins[idx] < rst[idx]) { 50 | count += calc(rst[idx], ins[idx]); 51 | } 52 | } 53 | 54 | System.out.println("result : " + count); 55 | return count; 56 | } 57 | 58 | private static int calc(char c, char i) { // 2, 1 59 | int x = Character.getNumericValue(c); 60 | int y = Character.getNumericValue(i); 61 | 62 | return x - y; 63 | } 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/structure/StackExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.structure; 2 | 3 | import java.util.NoSuchElementException; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 데이터를 순차적으로 저장하는 자료구조(브라우저 히스토리등). LIFO(Last In, First Out) 구조로 새로운 데이터는 스택의 최 상위에 위치하고 추출시 최상위 데이터를 가져올 수 있다 8 | * pop(추출) 9 | * - 가장 최 상위에 위치한 자료를 추출한 후에 스택에서 제거한다. 이 작업은 O(1)의 복잡도를 가진다 10 | * push(삽입) 11 | * - 스택의 최 상위에 새로운 자료를 삽입한다. 이 작업은 O(1)의 복잡도를 가진다 12 | * isEmpty 13 | * - 스택이 empty 상태인지 확인한다 14 | * clear 15 | * - 스택에 존재하는 모든 자료들을 삭제한다 16 | * peek 17 | * - 가장 최 상위에 위치한 자료를 추출한다. pop 메소드와는 달리 스택에서 제거하지는 않는다.이 작업은 O(1)의 복잡도를 가진다 18 | */ 19 | public class StackExample { 20 | private int[] array; 21 | private int cursor = 0; 22 | 23 | public StackExample(int stackSize) { 24 | this.array = new int[stackSize]; 25 | } 26 | 27 | public static void main(String[] args) { 28 | StackExample stack = new StackExample(4); 29 | 30 | stack.push(1); // 저장 31 | stack.push(2); 32 | stack.push(3); 33 | stack.push(4); 34 | stack.push(5); 35 | 36 | System.out.println(stack.pop()); 37 | System.out.println(stack.peek()); 38 | System.out.println(stack.pop()); 39 | } 40 | 41 | private int peek() { 42 | return array[cursor - 1]; 43 | } 44 | 45 | private int pop() { 46 | if (cursor > 0) { 47 | return array[--cursor]; 48 | } else { 49 | throw new NoSuchElementException(); 50 | } 51 | } 52 | 53 | private void push(int i) { 54 | if (cursor < array.length) { 55 | array[cursor++] = i; 56 | System.out.println("push completed"); 57 | } else { 58 | System.out.println("stack is full"); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/TimeDiffCalculator.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | import java.time.temporal.ChronoUnit; 6 | 7 | public class TimeDiffCalculator { 8 | 9 | public static void main(String[] args) { 10 | String inputDateTime = "2023-07-27 10:20:00"; 11 | LocalDateTime givenDateTime = LocalDateTime.parse(inputDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); 12 | LocalDateTime currentDateTime = LocalDateTime.now(); 13 | calculateDateTimeDiff(givenDateTime, currentDateTime); 14 | } 15 | 16 | private static void calculateDateTimeDiff(LocalDateTime givenDateTime, 17 | LocalDateTime currentDateTime) { 18 | long minutesDifference = getTimeDiff(givenDateTime, currentDateTime, ChronoUnit.MINUTES); 19 | long hoursDifference = getTimeDiff(givenDateTime, currentDateTime, ChronoUnit.HOURS); 20 | long daysDifference = getTimeDiff(givenDateTime, currentDateTime, ChronoUnit.DAYS); 21 | 22 | printTimeDiff(minutesDifference, hoursDifference, daysDifference); 23 | } 24 | 25 | private static long getTimeDiff(LocalDateTime givenDateTime, LocalDateTime currentDateTime, ChronoUnit unit) { 26 | return unit.between(givenDateTime, currentDateTime); 27 | } 28 | 29 | private static void printTimeDiff(long minutesDifference, long hoursDifference, 30 | long daysDifference) { 31 | if (minutesDifference < 1) { 32 | System.out.println("1분 전"); 33 | } else if (minutesDifference < 60) { 34 | System.out.println(minutesDifference + "분 전"); 35 | } else if (hoursDifference < 24) { 36 | System.out.println(hoursDifference + "시간 전"); 37 | } else { 38 | System.out.println(daysDifference + "일 전"); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/structure/QueueExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.structure; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.NoSuchElementException; 6 | 7 | 8 | /** 9 | * @Author : CodeVillains 10 | * @Description : FIFO 형태의 자료 구조(프린터 출력 등) , 배열이나 리스트 링크드 리스트 등을 통해 구현할 수 있다. 11 | * 연결 리스트를 이용하여 큐를 구현할 경우 데이터가 저장될 큐의 크기를 미리 지정하지 않아도 되며 배열처럼 front 보다 작은 인덱스 공간(삭제한 공간)을 낭비하지 않아도 된다는 장점을 가지고 있다. 12 | * 삽입 - insert, 삭제(추출) - remove, 읽기 - 13 | * Peek Enqueue(삽입) - 큐(Queue)의 끝에 새로운 자료를 삽입한다. 이 작업은 O(1)의 복잡도를 가진다 14 | * Dequeue(제거) - 큐(Queue)의 가장 첫 위치에 존재하는 자료를 반환하고 제거한다. 이 작업은 O(1)의 복잡도를 가진다 Peek - 큐(Queue)의 처음에 존재하는 자료를 반환한다. Dequeue 메소드와는 달리, 처음에 존재하는 자료를 제거하지는 않는다. 15 | * isEmpty - 큐(Queue) 가 Empty 상태인지 확인한다. clear - 큐(Queue) 내부의 모든 자료들을 삭제한다. 16 | */ 17 | public class QueueExample { 18 | 19 | private List queue = new ArrayList<>(); 20 | 21 | public void enqueue(Integer data) { 22 | queue.add(data); 23 | } 24 | 25 | public Integer dequeue() { 26 | if (queue.isEmpty()) { 27 | System.out.println("Queue is Empty"); 28 | throw new NoSuchElementException(); 29 | } 30 | 31 | return queue.remove(0); 32 | } 33 | 34 | public Boolean isEmpty() { 35 | return queue.isEmpty(); 36 | } 37 | 38 | public Integer peek() { 39 | return queue.get(0); 40 | } 41 | 42 | public static void main(String[] args) { 43 | QueueExample queue = new QueueExample(); 44 | queue.enqueue(2); 45 | queue.enqueue(1); 46 | queue.enqueue(3); 47 | queue.enqueue(4); 48 | System.out.println("Queue peek = " + queue.peek()); 49 | remove(queue); 50 | 51 | queue.enqueue(7); 52 | queue.enqueue(8); 53 | queue.enqueue(9); 54 | queue.dequeue(); 55 | remove(queue); 56 | 57 | } 58 | 59 | private static void remove(QueueExample queue) { 60 | while (!queue.isEmpty()) { 61 | System.out.println("Element : " + queue.dequeue()); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/PlusMinusGroup.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 주어진 배열의 음수, 양수, 0의 갯수를 파악하여 비율로 표시하라. 단, 소수점 6자리까지 표현한다. 8 | */ 9 | public class PlusMinusGroup { 10 | 11 | public static void main(String[] args) { 12 | int[] numbers = {-12, 33, -4, 0, 0, 9, 1, -2, 11, 0 }; 13 | 14 | float[] items = itemCount(numbers, numbers.length); 15 | // Arrays.stream 이용시 16 | // float[] items = itemCount(numbers); 17 | 18 | // 소수점 아래 6자리까지 출력 19 | System.out.printf("positive : %.6f\n", items[0]); 20 | System.out.printf("negatives : %.6f\n", items[1]); 21 | System.out.printf("zero : %.6f\n", items[2]); 22 | } 23 | 24 | private static float[] itemCount(int[] numbers, int length) { 25 | int positives = 0; 26 | int negatives = 0; 27 | int zeros = 0; 28 | 29 | for (int i = 0; i < length; i++) { 30 | if (numbers[i] > 0) { 31 | positives++; 32 | } else if (numbers[i] < 0) { 33 | negatives++; 34 | } else { 35 | zeros++; 36 | } 37 | } 38 | 39 | float point = (float) length; 40 | float positive = positives / point; 41 | float negative = negatives / point; 42 | float zero = zeros / point; 43 | 44 | float[] results = {positive, negative, zero}; 45 | return results; 46 | } 47 | 48 | private static float[] itemCount(int[] numbers) { 49 | long positives = Arrays.stream(numbers).filter(num -> num > 0).count(); 50 | long negatives = Arrays.stream(numbers).filter(num -> num < 0).count(); 51 | long zeros = Arrays.stream(numbers).filter(num -> num == 0).count(); 52 | 53 | float point = (float) numbers.length; 54 | float positive = positives / point; 55 | float negative = negatives / point; 56 | float zero = zeros / point; 57 | 58 | float[] results = {positive, negative, zero}; 59 | return results; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 따로 메모리를 사용하지 않는다. 현재 있는 메모리 안에서 정렬하기 때문에 효율이 좋음 피봇을 하나 정해 피봇보다 작은 아이템은 왼쪽에 큰 것은 8 | * 오른쪽에 위치하고 왼쪽 아이템, 오른쪽 아이템을 각각 quick sort로 리컬시브하게 연산한다. performance : O(n log n), worst case 9 | * O(n^2) : 이미 정렬된 상태에서 실행할 경우 space complexity : O(log n) 10 | */ 11 | public class QuickSort { 12 | 13 | public static void main(String[] args) { 14 | int[] array = {9, 2, 4, 7, 3, 7, 10}; 15 | 16 | int start = 0; 17 | int end = array.length - 1; 18 | quickSort(array, start, end); 19 | System.out.println(Arrays.toString(array)); 20 | } 21 | 22 | private static void quickSort(int[] array, int start, int end) { 23 | // low - index 시작점, high - index 끝점 24 | if (vilid(array, start, end)) { 25 | return; 26 | } 27 | 28 | // 피봇을 정한다. 29 | int middle = start + (end - start) / 2; 30 | int pivot = array[middle]; 31 | 32 | // 왼쪽은 피봇보다 작고 오른쪽은 피봇보다 커야 한다. 33 | int low = start; 34 | int high = end; 35 | 36 | while (low <= high) { 37 | while (array[low] < pivot) { 38 | low++; 39 | } 40 | 41 | while (array[high] > pivot) { 42 | high--; 43 | } 44 | 45 | if (low <= high) { 46 | int temp = array[low]; 47 | array[low] = array[high]; 48 | array[high] = temp; 49 | low++; 50 | high++; 51 | } 52 | } 53 | 54 | if (start < high) { 55 | quickSort(array, start, high); 56 | } 57 | 58 | if (start > low) { 59 | quickSort(array, low, end); 60 | } 61 | 62 | } 63 | 64 | private static boolean vilid(int[] array, int low, int high) { 65 | if (array.length == 0 || array == null) { 66 | return true; 67 | } 68 | if (low >= high) { 69 | return true; 70 | } 71 | return false; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/complexity/ComplexityTest.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.complexity; 2 | 3 | import java.util.Random; 4 | 5 | public class ComplexityTest { 6 | public static void main(String[] args) { 7 | int[] arr = new int[10000000]; // 큰 배열 생성 8 | int target = 9999999; // 검색할 요소 (배열의 마지막 요소) 9 | 10 | // 배열에 무작위 데이터 채우기 11 | Random random = new Random(); 12 | for (int i = 0; i < arr.length; i++) { 13 | arr[i] = random.nextInt(10000000); // 0부터 9999999 사이의 무작위 값 14 | } 15 | 16 | // 이진 검색 수행 및 실행 시간 측정 17 | long startTime = System.nanoTime(); 18 | int binarySearchResult = binarySearch(arr, target); 19 | long endTime = System.nanoTime(); 20 | long binarySearchTime = endTime - startTime; 21 | 22 | // 선형 검색 수행 및 실행 시간 측정 23 | startTime = System.nanoTime(); 24 | int linearSearchResult = linearSearch(arr, target); 25 | endTime = System.nanoTime(); 26 | long linearSearchTime = endTime - startTime; 27 | 28 | // 결과 출력 29 | System.out.println("# 이진 검색 결과: " + binarySearchResult); 30 | System.out.println("# 이진 검색 실행 시간: " + binarySearchTime + " ns"); 31 | 32 | System.out.println("# 선형 검색 결과: " + linearSearchResult); 33 | System.out.println("# 선형 검색 실행 시간: " + linearSearchTime + " ns"); 34 | } 35 | 36 | public static int binarySearch(int[] arr, int target) { 37 | int left = 0; 38 | int right = arr.length - 1; 39 | 40 | while (left <= right) { 41 | int mid = left + (right - left) / 2; 42 | if (arr[mid] == target) { 43 | return mid; 44 | } 45 | if (arr[mid] < target) { 46 | left = mid + 1; 47 | } else { 48 | right = mid - 1; 49 | } 50 | } 51 | return -1; 52 | } 53 | 54 | public static int linearSearch(int[] arr, int target) { 55 | for (int i = 0; i < arr.length; i++) { 56 | if (arr[i] == target) { 57 | return i; 58 | } 59 | } 60 | return -1; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/BinaryCadinality.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 8 | */ 9 | public class BinaryCadinality { 10 | 11 | public static void main(String[] args) { 12 | int[] numbers = {11,12,13,14,15,16,17}; 13 | 14 | int[] result = cardinalitySort(numbers); 15 | 16 | System.out.println("결과 = "); 17 | System.out.println(Arrays.toString(result)); 18 | 19 | } 20 | 21 | static int[] cardinalitySort(int[] nums) { 22 | Map unsortMap = new HashMap<>(); 23 | int size = nums.length; 24 | int[] arrays = new int[size]; 25 | for (int i = 0; i < size; i++) { 26 | String binaryString = Integer.toBinaryString(nums[i]); 27 | char[] chars = binaryString.toCharArray(); 28 | 29 | int count = 0; 30 | for (char c : chars) { 31 | if (c == '1') { 32 | count += Character.getNumericValue(c); 33 | } 34 | } 35 | unsortMap.put(nums[i], count); 36 | } 37 | 38 | Map valueMap = new LinkedHashMap<>(); 39 | Map keyMap = new LinkedHashMap<>(); 40 | unsortMap.entrySet().stream() 41 | .sorted(Map.Entry.comparingByKey()) 42 | .forEachOrdered(x -> valueMap.put(x.getKey(), x.getValue())); 43 | 44 | 45 | valueMap.entrySet().stream() 46 | .sorted(Map.Entry.comparingByValue()) 47 | .forEachOrdered(x -> keyMap.put(x.getKey(), x.getValue())); 48 | 49 | System.out.println("valueMap : " +valueMap); 50 | 51 | //keyMap = valueMap.entrySet().stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 52 | 53 | System.out.println("keyMap : " +keyMap); 54 | 55 | Iterator iter = keyMap.keySet().iterator(); 56 | 57 | int index = 0; 58 | while (iter.hasNext()) { 59 | arrays[index] = iter.next(); 60 | index++; 61 | } 62 | return arrays; 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/structure/DequeExample.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.structure; 2 | 3 | import java.util.Deque; 4 | import java.util.Iterator; 5 | import java.util.LinkedList; 6 | 7 | /** 8 | * @Author : CodeVillains 9 | * @Description : 큐의 양쪽에 삽입과 삭제가 모두 발생할 수 있는 큐로써 큐와 스택의 성질을 가지고 있는 자료 구조 10 | */ 11 | public class DequeExample { 12 | 13 | public static void main(String[] args) { 14 | Deque deque = new LinkedList<>(); 15 | 16 | // We can add elements to the queue in various ways 17 | deque.add("Element 1 (Tail)"); // add to tail // 4 18 | deque.addFirst("Element 2 (Head)"); // 3 19 | deque.addLast("Element 3 (Tail)"); // 5 20 | deque.push("Element 4 (Head)"); //add to head // 2 21 | deque.offer("Element 5 (Tail)"); // 6 22 | deque.offerFirst("Element 6 (Head)"); // 1 23 | deque.offerLast("Element 7 (Tail)"); // 7 24 | 25 | deque.forEach((str) -> System.out.println(str)); 26 | 27 | 28 | // Iterate through the queue elements. 29 | System.out.println("Standard Iterator"); 30 | Iterator iterator = deque.iterator(); 31 | while (iterator.hasNext()) 32 | System.out.println("\t" + iterator.next()); 33 | 34 | 35 | Iterator reverse = deque.descendingIterator(); 36 | System.out.println("Reverse Iterator"); 37 | while (reverse.hasNext()) 38 | System.out.println("\t" + reverse.next()); 39 | 40 | // Peek returns the head, without deleting 41 | // it from the deque 42 | System.out.println("Peek " + deque.peek()); 43 | System.out.println("After peek: " + deque); 44 | 45 | // Pop returns the head, and removes it from 46 | // the deque 47 | System.out.println("Pop " + deque.pop()); 48 | System.out.println("After pop: " + deque); 49 | 50 | // We can check if a specific element exists 51 | // in the deque 52 | System.out.println("Contains element 3: " + 53 | deque.contains("Element 3 (Tail)")); 54 | 55 | // We can remove the first / last element. 56 | deque.removeFirst(); 57 | deque.removeLast(); 58 | System.out.println("Deque after removing " + 59 | "first and last: " + deque); 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/loadbalancer/LeastConnectionsLoadBalancer.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.loadbalancer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public class LeastConnectionsLoadBalancer { 9 | private List serverList; 10 | // 서버 연결수를 측정하기 위해 (서버, 연결수)의 HashMap을 사용 11 | private Map connectionsCountMap; 12 | 13 | public LeastConnectionsLoadBalancer(List serverList) { 14 | this.serverList = new ArrayList<>(serverList); // serverList 복사 15 | this.connectionsCountMap = new HashMap<>(); 16 | // 서버 추가후 연결수는 초기화함 17 | for (String server : serverList) { 18 | connectionsCountMap.put(server, 0); 19 | } 20 | } 21 | 22 | public synchronized String getNextServer() { 23 | String nextServer = null; 24 | int minConnections = Integer.MAX_VALUE; 25 | 26 | for (String server : serverList) { 27 | int connections = connectionsCountMap.get(server); 28 | if (connections < minConnections) { 29 | minConnections = connections; 30 | nextServer = server; 31 | } 32 | } 33 | 34 | connectionsCountMap.put(nextServer, connectionsCountMap.get(nextServer) + 1); 35 | return nextServer; 36 | } 37 | 38 | // 서버 연결 수 감소 39 | public synchronized void releaseConnection(String server) { 40 | int connections = connectionsCountMap.get(server); 41 | if (connections > 0) { 42 | connectionsCountMap.put(server, connections - 1); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | List serverList = List.of("1번 서버", "2번 서버", "3번 서버"); 48 | LeastConnectionsLoadBalancer loadBalancer = new LeastConnectionsLoadBalancer(serverList); 49 | 50 | // 요청을 분산하여 처리 51 | for (int i = 0; i < 10; i++) { 52 | String server = loadBalancer.getNextServer(); 53 | System.out.println("요청 " + (i + 1) + " 번째 " + server+ "로 진입"); 54 | } 55 | 56 | // 서버1의 연결 수를 2회 감소 57 | loadBalancer.releaseConnection("1번 서버"); 58 | loadBalancer.releaseConnection("1번 서버"); 59 | 60 | // 추가요청 61 | for (int i = 0; i < 5; i++) { 62 | String server = loadBalancer.getNextServer(); 63 | System.out.println("추가 요청 " + (i + 1) + " 이 연결된 서버 = " + server); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/ComplexSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | import org.apache.commons.collections4.comparators.ComparatorChain; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | 12 | 13 | public class ComplexSort { 14 | 15 | private static final Logger logger = LoggerFactory.getLogger(ComplexSort.class); 16 | private static List products = new ArrayList<>(); 17 | 18 | public static void main(String args[]) { 19 | prepareData(); 20 | 21 | ComparatorChain chain = new ComparatorChain(); 22 | //비교할 대상을 각 Comparator로 작성 23 | chain.addComparator(comparatorPrdId); // 상품아이디 정렬 24 | chain.addComparator(comparatorPrdSize); // 상품사이즈 정렬 25 | 26 | Collections.sort(products, chain); 27 | 28 | consoleLog(); 29 | } 30 | 31 | /* 32 | public static Comparator comparatorPrdId = new Comparator() { 33 | @Override 34 | public int compare(Product o1, Product o2) { 35 | return o1.getPrdId().compareToIgnoreCase(o2.getPrdId()); 36 | } 37 | }; 38 | 39 | public static Comparator comparatorPrdSize = new Comparator() { 40 | @Override 41 | public int compare(Product o1, Product o2) { 42 | return o1.getPrdSize().compareTo(o2.getPrdSize()); 43 | } 44 | }; 45 | */ 46 | 47 | /** 48 | * 상품 아이디를 정렬한다. 49 | */ 50 | public static Comparator comparatorPrdId = (o1, o2) -> 51 | o1.getPrdId().compareToIgnoreCase(o2.getPrdId()); 52 | 53 | /** 54 | * 상품의 사이즈를 정렬한다. 55 | */ 56 | public static Comparator comparatorPrdSize = Comparator.comparing(Product::getPrdSize); 57 | 58 | /** 59 | * 대상 객체의 출력 기능 60 | */ 61 | private static void consoleLog() { 62 | logger.info("########## 출력 시작 #########"); 63 | for (Product product : products) { 64 | logger.info("Print : {} = {}", product.getPrdId(), product.getPrdSize()); 65 | } 66 | } 67 | 68 | /** 69 | * 미리 데이터를 생성함 70 | */ 71 | private static void prepareData() { 72 | products.add(new Product("tshirt", 110)); 73 | products.add(new Product("tshirt", 90)); 74 | products.add(new Product("tshirt", 100)); 75 | products.add(new Product("tshirt", 95)); 76 | products.add(new Product("tshirt", 105)); 77 | 78 | products.add(new Product("shoes", 270)); 79 | products.add(new Product("shoes", 260)); 80 | products.add(new Product("shoes", 275)); 81 | 82 | products.add(new Product("clothes", 44)); 83 | products.add(new Product("clothes", 55)); 84 | products.add(new Product("clothes", 66)); 85 | } 86 | } -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/Bracket.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz; 2 | 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | /** 7 | * @Author : CodeVillains 8 | * @Description : 지정된 괄호들의 밸런스가 맞는지 검증 9 | */ 10 | public class Bracket { 11 | /* 입력값 12 | 3 13 | {[()]} 14 | {[(])} 15 | {{[[(())]]}} 16 | */ 17 | 18 | public static void main(String[] args) { 19 | Scanner in = new Scanner(System.in); 20 | int t = in.nextInt(); 21 | for (int a0 = 0; a0 < t; a0++) { 22 | String expression = in.next(); 23 | System.out.println((isBalanced(expression)) ? "YES" : "NO"); 24 | } 25 | } 26 | 27 | public static boolean isBalanced(String expression) { 28 | Stack stack = new Stack<>(); 29 | 30 | for (int i = 0; i < expression.length(); i++) { 31 | String ch = expression.substring(i, i + 1); 32 | 33 | if (ch.equals("[") || ch.equals("{") || ch.equals("(")) { 34 | stack.push(ch); 35 | } else { 36 | if (ch.equals(")")) { 37 | // 스택이 비어있다면, 밸런스가 맞지 않는 것이므로 false를 반환 38 | if (stack.empty()) { 39 | return false; 40 | } 41 | if (stack.peek().equals("(")) { 42 | stack.pop(); 43 | } 44 | } else if (ch.equals("}")) { 45 | if (stack.empty()) { 46 | return false; 47 | } 48 | if (stack.peek().equals("{")) { 49 | stack.pop(); 50 | } 51 | } else if (ch.equals("]")) { 52 | if (stack.empty()) { 53 | return false; 54 | } 55 | if (stack.peek().equals("[")) { 56 | stack.pop(); 57 | } 58 | } 59 | /* 60 | *조건문이 다소 많다고 느낀다면 아래와 같이 표현할 수 있다. 61 | 62 | if (stack.empty()) { 63 | return false; 64 | } 65 | 66 | // 스택의 가장 위에 있는 괄호와 현재 괄호가 짝이 맞는지 확인하고, 맞으면 스택에서 제거. 67 | if (ch.equals(")") && stack.peek().equals("(") || 68 | ch.equals("}") && stack.peek().equals("{") || 69 | ch.equals("]") && stack.peek().equals("[")) { 70 | stack.pop(); 71 | } else { // 짝이 맞지 않는 경우 false를 반환. 72 | return false; 73 | } 74 | */ 75 | } 76 | } 77 | return stack.empty(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/lfu/LFUCache.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.lfu; 2 | 3 | import java.util.AbstractMap; 4 | import java.util.HashMap; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.PriorityQueue; 8 | 9 | class LFUCache { 10 | private final int capacity; 11 | private final Map cache; 12 | private final Map frequency; 13 | // 우선순위 큐 (가장 낮은 값이 우선순위가 높다) 14 | private final PriorityQueue> minHeap; 15 | 16 | public LFUCache(int capacity) { 17 | this.capacity = capacity; 18 | this.cache = new LinkedHashMap<>(capacity, 0.75f, true); 19 | this.frequency = new HashMap<>(capacity); 20 | // 우선순위 큐의 빈도수 비교 (갸장 낮은 빈도수를 가진 항목이 맨 위에 위치) 21 | this.minHeap = new PriorityQueue<>((e1, e2) -> e1.getValue() - e2.getValue()); 22 | } 23 | 24 | public V get(K key) { 25 | // 빈도수 증가 처리 26 | if (cache.containsKey(key)) { 27 | int freq = frequency.get(key); 28 | frequency.put(key, freq + 1); 29 | return cache.get(key); 30 | } 31 | return null; 32 | } 33 | 34 | public void put(K key, V value) { 35 | if (capacity == 0) { 36 | return; 37 | } 38 | 39 | if (cache.size() >= capacity) { 40 | evictLFU(); 41 | } 42 | 43 | cache.put(key, value); 44 | frequency.put(key, 1); 45 | // minHeap에 항목을 추가 46 | minHeap.offer(new AbstractMap.SimpleEntry<>(key, 1)); 47 | } 48 | 49 | private void evictLFU() { 50 | // 가장 낮은 항목의 key 조회 51 | Map.Entry entry = minHeap.poll(); 52 | K lfuKey = entry.getKey(); 53 | cache.remove(lfuKey); 54 | frequency.remove(lfuKey); 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | StringBuilder sb = new StringBuilder(); 60 | for (Map.Entry entry : cache.entrySet()) { 61 | sb.append(entry.getKey()).append(": ").append(entry.getValue()).append(", "); 62 | } 63 | return sb.toString(); 64 | } 65 | 66 | public static void main(String[] args) { 67 | LFUCache cache = new LFUCache<>(3); // LFU 캐시 크기를 3으로 설정 68 | 69 | cache.put(1, "첫번째 항목"); 70 | cache.put(2, "두번째 항목"); 71 | cache.put(3, "세번째 항목"); 72 | System.out.println("초기값 : " + cache); 73 | System.out.println("두번째 항목, 세번째 항목 호출 빈도 증가"); 74 | cache.get(2); 75 | cache.get(3); 76 | cache.get(2); 77 | System.out.println("증가 후 값: " + cache); 78 | cache.put(4, "네번째 항목"); 79 | System.out.println("네번째 삽입 후 값 : " + cache); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/collection/sort/actor/FilmFestival.java: -------------------------------------------------------------------------------- 1 | package net.harunote.collection.sort.actor; 2 | 3 | import static java.util.Arrays.asList; 4 | import static java.util.List.of; 5 | 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | import java.util.Collections; 9 | import java.util.List; 10 | import java.util.Set; 11 | import java.util.TreeSet; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | //청룡영화제 수상자 예제 16 | public class FilmFestival { 17 | 18 | private static final Logger logger = LoggerFactory.getLogger(FilmFestival.class); 19 | 20 | public static void main(String args[]) { 21 | /* 청룡영화제 10년간 수상작 22 | 33회(2012) - 최민식(《범죄와의 전쟁: 나쁜놈들 전성시대》) 23 | 34회(2013) - 황정민(《신세계》) 24 | 35회(2014) - 송강호(《변호인》) 25 | 36회(2015) - 유아인(《사도》) 26 | 37회(2016) - 이병헌(《내부자들》) 27 | 38회(2017) - 송강호(《택시운전사》) 28 | 39회(2018) - 김윤석(《1987》) 29 | 40회(2019) - 정우성(《증인》) 30 | 41회(2020) - 유아인(《소리도 없이》) 31 | 42회(2021) - 설경구(《자산어보》) 32 | 43회(2022) - 박해일(《헤어질 결심》) 33 | */ 34 | Actor[] actors = new Actor[]{ 35 | new Actor("송강호", "변호인", 2014), 36 | new Actor("유아인", "소리도 없이", 2020), 37 | new Actor("황정민", "신세계", 2013), 38 | new Actor("송강호", "택시운전사", 2017), 39 | new Actor("유아인", "사도", 2015), 40 | new Actor("김윤석", "1987", 2018), 41 | new Actor("설경구", "자산어보", 2021), 42 | new Actor("최민식", "범죄와의 전쟁: 나쁜놈들 전성시대", 2012), 43 | new Actor("박해일", "헤어질 결심", 2022), 44 | new Actor("이병헌", "내부자들", 2016), 45 | new Actor("정우성", "증인", 2019) 46 | }; 47 | 48 | logger.info("### 정렬 전 ###"); 49 | consoleLog(of(actors)); 50 | 51 | Arrays.sort(actors); 52 | logger.info("### 기본 정렬 후 (배우이름) ###"); 53 | consoleLog(of(actors)); 54 | 55 | List list = asList(actors); // 배열을 리스트로 56 | Collections.shuffle(list); // 리스트의 순서를 섞음. 57 | 58 | logger.info("### List shuffle 후 ###"); 59 | consoleLog(list); 60 | 61 | // 리스트를 정렬 (클래스에 정의된 기본정렬) 62 | Collections.sort(list); 63 | 64 | logger.info("### List 기본 정렬 후 ###"); 65 | consoleLog(list); 66 | 67 | // 디폴트 정렬할 수 있는 TreeSet을 만든다 68 | Set set = new TreeSet<>(list); 69 | 70 | logger.info("### treeset 적용 후 ###"); 71 | consoleLog(set); 72 | 73 | // 연동별로 적용한 set 74 | Set yearSet = new TreeSet<>(new PrizeYearComparator()); 75 | yearSet.addAll(list); 76 | 77 | logger.info("### 최신 연도별 정렬 후 ###"); 78 | consoleLog(yearSet); 79 | 80 | } 81 | 82 | private static void consoleLog(Collection collection) { 83 | for (Actor actor : collection) { 84 | logger.info(actor.toString()); 85 | } 86 | } 87 | } 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/algorithm/sort/MergeSort.java: -------------------------------------------------------------------------------- 1 | package net.harunote.algorithm.sort; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @Author : CodeVillains 7 | * @Description : 병합정렬 (Divide & Conquer) : 안정적인 정렬 주워진 배열을 두 부분씩 나누워 정렬한 후 하나로 합치는 방식 두 번의 재귀 호출과 한 8 | * 번의 합병으로 구성되며 재귀 호출 시 배열 크기가 절반으로 줄어 들어 깊이가 log n 으로 된다. 즉, 두 배열의 합은 두 배열의 크기의 합에 비례 함으로 전체 수행 시간 9 | * 복잡도는 최악, 최선, 평균 모두 O(n log n). 분할정복 방식의 알고리즘의 한 종류 (1/2 씩 분할)… Performance : O(n log n) 10 | */ 11 | public class MergeSort { 12 | 13 | public static void main(String[] args) { 14 | Integer[] a = {2, 6, 3, 5, 1}; 15 | mergeSort(a); 16 | System.out.println(Arrays.toString(a)); 17 | } 18 | 19 | private static Comparable[] mergeSort(Comparable[] list) { 20 | // 리스트가 1 이하이면 연산할 필요 없음 21 | if (list.length <= 1) { 22 | return list; 23 | } 24 | 25 | // 리스트를 반으로 나누어 두 부분으로 분리 26 | Comparable[] first = new Comparable[list.length / 2]; // 5 일 경우 2.5 (2) 27 | Comparable[] second = new Comparable[list.length - first.length]; // 5 - 2 : 3개의 배열 요소를 처리 28 | 29 | // 배열에서 원하는 요소를 부분을 복사한다. 30 | // 원본, 원본 시작점, 복사본, 복사본 시작점, 길이 31 | System.arraycopy(list, 0, first, 0, first.length); // 첫 파트 배열 카피 list, 0, first, 0, 2 32 | System.arraycopy(list, first.length, second, 0, 33 | second.length); // 두번째 파트 배열 카피 list, 2, second, 0, 3 34 | 35 | // 재귀 호출로 각 요소를 분리한다.(첫 번째 배열 분해 후 두번째 배열 분해) 36 | mergeSort(first); 37 | mergeSort(second); 38 | 39 | // 각 배열을 병합하여 원래 배열을 덮어쓴다. 40 | merged(first, second, list); 41 | 42 | return list; 43 | } 44 | 45 | private static void merged(Comparable[] first, Comparable[] second, Comparable[] result) { 46 | // 첫번째 배열의 인덱스 위치 - 첫 요소 부터 시작 47 | int firstIndex = 0; 48 | 49 | // 두번째 배열의 인덱스 위치 - 첫 요소 부터 시작 50 | int secondIndex = 0; 51 | 52 | // 병합된 배의 인덱스 위치 - 첫번째 위치부터 시작 53 | int merged = 0; 54 | 55 | // 첫 배열의 요소와 두번째 배열의 요소를 비교함 56 | // 그 중 작은 요소를 배열병합에 저장 57 | while (firstIndex < first.length && secondIndex < second.length) { 58 | System.out.println( 59 | "first[firstIndex] : " + first[firstIndex] + " second[secondIndex] : " 60 | + second[secondIndex] + " result = " + 61 | first[firstIndex].compareTo(second[secondIndex])); 62 | 63 | if (first[firstIndex].compareTo(second[secondIndex]) < 0) { 64 | result[merged] = first[firstIndex]; 65 | firstIndex++; 66 | } else { 67 | result[merged] = second[secondIndex]; 68 | secondIndex++; 69 | } 70 | merged++; 71 | } 72 | 73 | System.arraycopy(first, firstIndex, result, merged, first.length - firstIndex); 74 | System.arraycopy(second, secondIndex, result, merged, second.length - secondIndex); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/net/harunote/quiz/practice/HashtableRansomNote.java: -------------------------------------------------------------------------------- 1 | package net.harunote.quiz.practice; 2 | 3 | import java.util.Hashtable; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | /** 9 | * @Description : The first line contains two space-separated integers describing the respective values of 10 | * (the number of words in the magazine) and (the number of words in the ransom note). 11 | * The second line contains space-separated strings denoting the words present in the magazine. 12 | * The third line contains space-separated strings denoting the words present in the ransom note. 13 | * 14 | * sample 15 | * 6 4 16 | * give me one grand today night 17 | * give one grand today 18 | */ 19 | public class HashtableRansomNote { 20 | Map magazineMap; 21 | Map noteMap; 22 | 23 | public HashtableRansomNote(String magazine, String note) { 24 | String[] ma = magazine.split("\\s"); 25 | String[] no = note.split("\\s"); 26 | 27 | magazineMap = new Hashtable<>(); 28 | noteMap = new Hashtable<>(); 29 | 30 | int init = 1; 31 | for (String str : no) { 32 | if (noteMap.containsKey(str)) { 33 | noteMap.put(str, noteMap.get(str) + 1); 34 | } else { 35 | noteMap.put(str, init); 36 | } 37 | } 38 | System.out.println("1 note : " + noteMap.toString()); 39 | 40 | 41 | 42 | int count = 1; 43 | for (String str : ma) { 44 | if (magazineMap.containsKey(str)) { 45 | magazineMap.put(str, magazineMap.get(str) + 1); 46 | } else { 47 | magazineMap.put(str, count); 48 | } 49 | } 50 | 51 | System.out.println("2 magazineMap : " + magazineMap.toString()); 52 | 53 | 54 | } 55 | 56 | public boolean solve() { 57 | boolean result = false; 58 | Set keys = magazineMap.keySet(); 59 | 60 | for (String str : keys) { 61 | System.out.println("str : " + str); 62 | System.out.println("noteMap.containsKey(str) : " + noteMap.containsKey(str)); 63 | if (noteMap.containsKey(str)) { 64 | if (magazineMap.get(str) >= noteMap.get(str)) { 65 | noteMap.remove(str); 66 | } 67 | } 68 | } 69 | 70 | if (noteMap.isEmpty()) { 71 | result = true; 72 | } 73 | 74 | return result; 75 | } 76 | 77 | public static void main(String[] args) { 78 | Scanner scanner = new Scanner(System.in); 79 | int m = scanner.nextInt(); 80 | int n = scanner.nextInt(); 81 | // Eat whitespace to beginning of next line 82 | scanner.nextLine(); 83 | 84 | HashtableRansomNote s = new HashtableRansomNote(scanner.nextLine(), scanner.nextLine()); 85 | scanner.close(); 86 | 87 | boolean answer = s.solve(); 88 | if(answer) 89 | System.out.println("Yes"); 90 | else System.out.println("No"); 91 | 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > # 개발자 기술 면접 노트 소스 코드 2 | > Tech interview 관련 소스 코드들의 위치 및 책에서 다루고 있는 주제들을 정리하였습니다.
3 | > 책에는 책의 분량문제로 극히 일부분의 코드만 다뤘고 아래의 내용을 참고하여 책과 같이 코드를 봐주시기 바랍니다. 4 | > - 알고리즘이나 콜렉션의 경우 오래전 작성한 소스도 있어서 최신 스타일로 바꾸지 않은 에전 코드들을 확인할 수 있습니다. 5 | > - 해당 코드들을 모던 자바 스타일로 변환하는 훈련을 하세요. 6 | > - 함수를 쓰지 않은 형태의 내부 동작들에 대해서 확인할 수 있습니다. 7 | > - 고전 형태의 코드가 동작을 이해하는데 더 유용할 수 있으므로 변환하지는 않았으니 참고하세요. 8 | > - /src/main/java 하위에 net/harunote 패키지부터 주제별 코드를 모아놨습니다. 9 | > - 본 코드들은 제 개인 Repository에 흩어져 있던 것들을 책을 출간하며 현재의 Repository에 모은 것입니다. 10 | > - 각각의 커밋 이력들은 Origin Repository에서 확인할 수 있습니다. (주로 2016~2018년 커밋 내역) 11 | > - 최초 커밋 정보들도 정리하였고, 코드가 바뀌거나 모으는 과정에서 최신 버전으로 변경된 부분도 있으니 주석등을 통해 코드 생성일 정보등을 참고할 수 있습니다. 12 | 13 | 14 | 15 | # 📖 Book 16 | ### [연봉 앞자리를 바꾸는] 개발자 기술 면접 노트 17 | ###### 2024.03.20 한빛미디어 이남희 지음 18 | 19 | 20 | > Yes24 - https://www.yes24.com/Product/Goods/125554439 21 | > 22 | > KyoboBooks - https://product.kyobobook.co.kr/detail/S000212738756 23 | 24 | 25 | # Algorithm 패키지 26 | 알고리즘 관련 소스코드 27 | > Commits on Jun 30, 2017 28 | > 29 | > Origin Repository : https://github.com/gliderwiki/java8/tree/master/src/main/java/algorithm 30 | 31 | - Complexity 32 | - binarySearch 33 | - linearSearch 34 | - LFU 35 | - LFU Cache 36 | - LRU 37 | - LRU Cache 38 | - Load Banancer 39 | - LeastConnections 40 | - RoundRobinLoad 41 | - Sort 42 | - ArraySort 43 | - BubbleSort 44 | - ComplexSort 45 | - InsertionSort 46 | - ListSort 47 | - MergeSort 48 | - QuickSort 49 | - SelectionSort 50 | - Map Comparator 51 | 52 | 53 | # Collection 패키지 54 | Collection Framework의 기본 개념 55 | > Commits on May 28, 2017 56 | > 57 | > https://github.com/gliderwiki/java8/commits/master/src/main/java/data 58 | > 59 | - 데이터구조 60 | - Deque 61 | - Queue 62 | - Stack 63 | - PriorityQueue 64 | 65 | - Set 인터페이스 66 | - List 인터페이스 67 | - Map 인터페이스 68 | - HashMap 클래스 69 | - TreeMap 클래스 70 | - LinkedHashMap 클래스 71 | - Hashtable 클래스 72 | 73 | - Collection을 이용한 정렬 74 | - Collecions.sort()를 이용한 정렬 75 | - Arrays.sort()를 이용한 정렬 76 | - Comparable과 Comparator를 통한 정렬 구현 77 | - Multi Column에 대한 정렬 처리 78 | 79 | # Pattern 80 | 주요 디자인 패턴에 대한 예제 정리. 81 | > Commits on Sep 9, 2016 82 | > 83 | > Repository : https://github.com/gliderwiki/designPattern 84 | - 디자인 패턴 85 | - Adapter 86 | - Command 87 | - Decorator 88 | - Facade 89 | - Factory method 90 | - Singleton 91 | - Strategy 92 | - Template Method 93 | 94 | # Java 8 95 | Java 8의 문법적 특징과 예제들. 96 | > Commits on Aug 22, 2016 97 | > 98 | > Repository : https://github.com/gliderwiki/java8 99 | - functional 100 | - consumer 101 | - function 102 | - predicate 103 | - supplier 104 | - lambda 105 | - comparator 106 | - runnable 107 | - parameterization 108 | 109 | # Quiz 110 | 각종 알고리즘 퀴즈 (몸풀기용) 모음, 유명한 문제 및 기본적인 퀴즈 훈련. 111 | 여러 알고리즘 훈련 사이트를 참고하거나, 자체적으로 만든 문제들을 포함. 112 |
113 | 코드가 이해 안될 경우 반드시 주석의 Description을 참고할것. 114 | > Commits on May 23, 2017 115 | > 116 | > https://github.com/gliderwiki/java8/tree/master/src/main/java/quiz 117 | 118 | 119 | # 정보 120 | #### Rerepository https://github.com/haru-note/tech-interview 121 | 122 | 123 | #### this source was moved from the link below. 124 | - https://github.com/gliderwiki/java-sample 125 | - https://github.com/gliderwiki/designPattern 126 | - https://github.com/gliderwiki/java8 127 | 128 | #### Collection of sources from 2016 to 2023 by VillainsCode -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | --------------------------------------------------------------------------------