Java

728x90
ArrayList<String> arrList = new ArrayList(Arrays.asList("aaa","bb","cccc"));


//1번째 방법
System.out.println(arrList);
//결과: [aaa, bb, cccc]



//2번째 방법
for(String str:arrList){
    System.out.print(str+" ");
    //결과: aaa bb cccc
}

System.out.println();

//3번째 방법
Iterator iter = arrList.iterator(); //Iterator 선언
while(iter.hasNext()){
    System.out.print(iter.next()+ " ");
    //결과: aaa bb cccc
}

결론

  1. ArrayList 그대로 출력
  2. for-each문 사용
  3. Iterator 사용
728x90
728x90
Object objToString = "test";
String str1 = objToString.toString();
String str2 = String.valueOf(objToString);
String str3 = (String) objToString;

System.out.println("str1 = " + str1);
System.out.println("str2 = " + str2);
System.out.println("str3 = " + str3);

Object nullObjToString = null;
//String str4 = nullObjToString.toString();
//System.out.println("str4 = " + str4);
String str5 = String.valueOf(nullObjToString);
System.out.println("str5 = " + str5);
String str6 = (String) nullObjToString;
System.out.println("str6 = " + str6);


Object objToInt = 3;
int int1 = Integer.parseInt(objToInt.toString());
int int2 = (int) objToInt;

System.out.println("int1 = " + int1);
System.out.println("int2 = " + int2);

/** result
str1 = test
str2 = test
str3 = test
str5 = null
str6 = null
int1 = 3
int2 = 3 **/

object to String 결론

  • .toString() NPE 발생
  • .valueOf()
  • (String) 예외 없이 모든 참조 유형에 널을 캐스팅할 수 있다. (추후체크)
  • (String)에 관한 StackOverflow
728x90

'Java > Java 개념' 카테고리의 다른 글

[Java] Error And Exception  (0) 2023.03.12
[Java] ArrayList 출력 방법 3가지  (0) 2023.03.12
[Java] test코드작성시 console을 통해 입력받는 방법  (0) 2023.03.12
[Java] 자바 문자열  (0) 2023.03.12
[JAVA] CompletableFuture  (0) 2023.02.12
728x90

String input = "aaaa,bbbbb,ccc";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);

테스트 코드에서 터미널로 입력이 필요한경우 위와 같은 코드로 입력을 넣을수 있다.

728x90

'Java > Java 개념' 카테고리의 다른 글

[Java] Error And Exception  (0) 2023.03.12
[Java] ArrayList 출력 방법 3가지  (0) 2023.03.12
[Java] Object를 String타입으로 변환  (0) 2023.03.12
[Java] 자바 문자열  (0) 2023.03.12
[JAVA] CompletableFuture  (0) 2023.02.12

[Java] 자바 문자열

2023. 3. 12. 23:26
728x90

String

String은 immutable하다. immutable과 mutable

따라서 수정을 필요로 할땐 이미 존재하는 객체이더라도 새로운 객체를 생성하여 재할당 하기 때문에 비효율 적인 부분이 존재한다. 이를 해결하기 위해 mutable한 Stringbuilder & StringBuffer에 대해 알아본다.

  • 참고사항
String a = "123";
String b = a;
String c = new String(b);

if(a==b){
    System.out.println("a, b같은 객체");
}
if(a==c){
    System.out.println("a, c같은 객체");
}
if(b==c){
    System.out.println("b,c 같은 객체");
}

//result a, b같은 객체

Type이 String인 객체들끼리 == 비교를 통해 같은 객체인지 확인할수있다. 이때 객체가아닌 String간 내용이 같은지 비교할땐 equals를 사용한다.

참고사항: length배열의 길이,length() 문자열의 길이 ,size() Collections의 size




StringBuilder & StringBuffer

Stringbuilder & StringBuffer는 muable하다 즉 수정을 하더라도 문자열을 추가할때마다 객체가 재할당 되는 형태가 아니다.

그렇다면 Stringbuilder & StringBuffer의 차이점은 무엇인가?

Stringbuilder & StringBuffer 의 가장큰 차이점은 동기화의 유무이다.

 

즉 StringBuilder는 synchronized 하지 않다. 즉, 스레드로부터 안전하지 않다. 둘 이상의 스레드가 동시에 StringBuilder 인스턴스에 액세스하면 결과를 예측할 수 없다. 하지만 StringBuilder는 동기화 오버헤드를 발생시키지 않기 때문에 일반적으로 StringBuffer보다 빠르다.

 

반면에 StringBuffer는 synchronized 하다. 즉 스레드로부터 안전하다. 여러 스레드가 동시에 StringBuffer 인스턴스에 액세스하면 액세스가 동기화되고 결과를 예측할 수 있다. 그러나 synchronized 하다는 특성때문에 StringBuilder보다 느리다.

728x90

[JAVA] CompletableFuture

2023. 2. 12. 18:17
728x90

CompletableFuture

CompletableFunture은 Asynchronous programming을 수행할수 있도록 java에서 제공하는 class이며,

기존 Future를 기반으로 외부에서 완료시킬수 있어 CompletableFuture라는 이름을 갖게 되었다.

CompletableFuture은 Future에서 할수없었던 여러 Future의 조합, 예외처리, callback 등록 등이 가능하다.

 

 

비동기 작업

  • runAsync
    • 반환값이 없는 경우
  • supplyAsync
    • 반환값이 있는 경우

runAsync

    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        System.out.println("runAsync");
    });
    future.get();
    System.out.println("main");

runAsync는 반환값이 없으므로 Void타입이고, 위 코드를 실행해보면 future가 별도의 쓰레드에서 실행이 된다.

supplyAsync

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            return "Hello, CompletableFuture!";
    });

    System.out.println("Before calling get()");
    String result = future.get();
    System.out.println("After calling get(): " + result);

supplyAsync는 runAsync와 달리 반환값이 존재한다. 따라서 비동기 작업의 결과를 받아올수 있다.

 

 

콜백

  • thenApply, thenAccept, thenRun
  • thenApply
    • 반환 값을 받아 다른 값을 반환한다.
    • 함수형 인터페이스 Function을 파라미터로 받는다
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        return "Hello, CompletableFuture!";
    }).thenApply(s -> {
        return s.toUpperCase();
    });

    System.out.println(future.get());

.thenApply를 통해 HELLO, COMPLETABLEFUTURE! 결과값을 얻을수 있다.

  • thenAccept
    • 반환 값을 받아 처리후 값을 반환하지 않는다.
    • 함수형 인터페이스 Consumer를 파라미터로 받는다.
    CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
        return "Hello, CompletableFuture!";
    }).thenAccept(s -> {
        System.out.println("thenAccept: " + s);
    });

.thenAccept를 통해 thenAccept: Hello, CompletableFuture! 결과값을 얻을수 있다.

  • thenRun
    • 반환 값을 받지 않고 다른 작업을 실행한다.
    • 함수형 인터페이스 Runnable을 파라미터로 받는다.
    CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
        return "Hello, CompletableFuture!";
    }).thenRun(() -> {
        System.out.println("thenRun");
    });

.thenRun()은 반환값을 받지않고 다른 작업을 실행하는 콜백이다. 위 코드 실행시 thenRun결과를 얻을수있다.

 

 

작업 조합

  • thenCompose, thenCombine, allOf, anyOf
  • thenCompose
    • 두 작업이 이어서 실행하도록 조합, 앞선 작업의 결과를 받아 사용할수있다.
    • 함수형 인터페이스 Function을 파라미터로 받는다.
    CompletableFuture<String> future1 = 
        CompletableFuture.supplyAsync(() -> "Hello");

    CompletableFuture<String> future2 = 
        future1.thenCompose(result -> 
            CompletableFuture.supplyAsync(() -> result + ", CompletableFuture!"));

    System.out.println("Result of thenCompose: " + future2.get());

.thenCompose를 통해 Result of thenCompose: Hello, CompletableFuture! 다음과 같은 결과를 얻을수있다.

  • thenCombine
    • 두 작업을 독립적으로 실행한후, 둘다 완료되었을떄 콜백을 실행한다.
    • 함수형 인터페이스 Function을 파라미터로 받는다.
    CompletableFuture<String> future3 = 
        CompletableFuture.supplyAsync(() -> "Hello");

    CompletableFuture<String> future4 = 
        CompletableFuture.supplyAsync(() -> ", CompletableFuture!");

    CompletableFuture<String> combinedFuture = 
        future3.thenCombine(future4, (result1, result2) -> result1 + result2);

    System.out.println("Result of thenCombine: " + combinedFuture.get());

thenCombine을 통해 독립적으로 실행된 future3과 future4의 결과를 조합해 future4에서 처리한다.

결과값은 Result of thenCombine: Hello, CompletableFuture!이다.

  • allOf
    • 여러 작업들을 동시에 실행하고, 모든 작업 결과에 콜백을 실행한다.
    CompletableFuture<String> future5 =
        CompletableFuture.supplyAsync(() -> "Hello");

    CompletableFuture<String> future6 =
        CompletableFuture.supplyAsync(() -> "CompletableFuture!");

    List<CompletableFuture<String>> futures = List.of(future5, future6);

    CompletableFuture<List<String>> result =
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList()));

    result.get().forEach(System.out::println);

allOf는 모든결과에 콜백이 적용되어 위 코드의 결과값이 아래와 같음을 알수있다.

Hello
CompletableFuture!

  • anyOf
  • 여러 작업들 중에서 가장 빨리 끝난 하나의 결과에 콜백을 실행한다.
    CompletableFuture<String> future7 = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            return "Hello";
    });

    CompletableFuture<String> future8 = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            return "CompletableFuture!";
    });

    CompletableFuture<Object> firstFuture = CompletableFuture.anyOf(future7, future8);
    System.out.println("Result of anyOf: " + firstFuture.get());

anyOf는 future7과 future8중 더빨리끝난 하나의 결과에 콜백을 실행하므로 결과값은

Result of anyOf: Hello이다.

예외처리

  • exceptionally
    • 발생한 에러를 받아 예외를 처리한다.
    • 함수형 인터페이스 Function을 파라미터로 받는다.
  • handle,handleAsync
    • (결과값,에러)를 반환받아 에러가 발생한 경우와 아닌 경우 모두를 처리할수있다.
    • 함수형 인터페이스 BiFunction을 파라미터로 받는다.

Reference

728x90

Java) Java-collection queue

2022. 11. 15. 13:42
728x90

queue = FIFO (First-In-First-out)  구조  

Enqueue = 큐 맨뒤에 데이터가 추가된다.

Dequeue = 큐 맨앞에 데이터가 삭제된다.

java에서 queue를 구현하기위해서는 LinkedList를 사용해 구현한다. 

 

return Method
boolean add(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
E element()
Retrieves, but does not remove, the head of this queue.
boolean offer(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
E peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.
E remove()
Retrieves and removes the head of this queue.

 

add와 offer은 queue에 값을 추가해준다는것은 동일하지만  add는 큐가 꽉차 더이상 값을 추가할수없을때 예외를 발생시키지만 offer는 추가실패를 의미하기위해 false를 return한다. 

poll() 과 remove도 마찬가지이다. poll()은 더이상 뺄 값이없을때 null을 return하지만 remove는 예외를 발생시킨다. (아래예시)

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
 
public class Main {
    
    public static void main(String[] args) throws IOException {
        Queue<Integer> queue = new LinkedList<Integer>();

        queue.add(1);
        queue.offer(2);

        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.poll()); // null 리턴
        System.out.println(queue.remove()); // 예외발생
        
        
       
    }
}

poll() -> null, remove -> 예외

peek() = 가장 앞에있는 값을 가리킨다. 이때도 peek()은 queue가 비어있으면 null 리턴

element() = queue가 비어있으면 예외 발생

public class Main {
    
    public static void main(String[] args) throws IOException {
        Queue<Integer> queue = new LinkedList<Integer>();

        queue.add(1);
        queue.offer(2);

        System.out.println(queue.peek()); // -> 1
        System.out.println(queue.element()); // -> 1
        
    }
}
public class Main {
    
    public static void main(String[] args) throws IOException {
        Queue<Integer> queue = new LinkedList<Integer>();

        System.out.println(queue.peek());
        System.out.println(queue.element());
            
    }
}

peek() -> null, element() -> 예외

 

728x90

+ Recent posts