본문 바로가기
JAVA/- Useful Code

[코테용] JAVA 자주 사용하는 문법

by 고고 뜌지 2024. 10. 21.

 

 

String

 - 불변(immutable)한 클래스 : '새로운 객체' 로 추가 및 변경됨

1. 메서드

  - String target = "안녕"

String.repeat(n) // 반복출력
target.repeat(5);   // 안녕안녕안녕안녕안녕
String.length() // Stirng 크기 확인
String.concat(n) // 문자열 합치기 
target.concat("이당") // 안녕이당
String.substring(n,j) // n의 index에서 j의 index까지 추출
"123456".substring(2,3) // 3
String.split(n) // 문자열을 n의 특정문자 기준으로 array로 자르기
"123 456".split(" ")  //["123","456"]
String.toCharArray() // char (문자1개) 타입의 array로 변환 
"안녕하세요".toCharArray() //[안, 녕, 하, 세, 요]
String.equals(a) "hello".equals("start")   // false
String.indexOf() "hello java".indexOf("java")  // 6
String.contains() "hello java".contains("java")  // true
String.charAt(a) "hello java".charAt(6)  // "j" 출력
String.replaceAll(a,b) "hello java".replaceAll("java", "world")  // hello world
String.format() String.format("i eat %s , count : %d", "apple", 3)  // i eat apple count : 3

 

StringBuffer

  - 가변(mutable)한 클래스 : "기존의 객체" 로 추가 및 변경 

  - 메소드가 String 랑 겹치는것이 많음

1. 메소드

append(value) StringBuffer sb = new StringBuffer("hello");
sb.append(" world");
String result = sb.toString()  //hello world 
insert(index,value) StringBuffer sb = new StringBuffer("jump to java");
sb.insert(0, "hello "); //hello jump to java
substring(start,end) StringBuffer sb = new StringBuffer("hello jump to java");
sb.substring(0,5);  // hello

 

 

Array

   - 길이가 선언된 배열은 수정 불가능 

1. 메소드

Arrays.toString(A) // Array의 값을 String으로 변환 
Arrays.length // 길이
Arrays.copyOf(a,b) // Arrays.copyOf(원본배열, 원본 배열에서 복사해올 길이)
// 배열의 선언된 길이 같이 변경됨 
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int[] copied = new int[15]; //배열길이 15

copied = Arrays.copyOf(arr,7);
System.out.println(Arrays.toString(copied);) //[1, 2, 3, 4, 5, 6, 7]  / 배열길이 7
System.arraycopy() //System.arraycopy(원본 배열, 원본 배열의 복사 시작 지점, 복사할 배열, 복사할 배열의 시작 지점, 복사할 요소의 개수)
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int[] copied = new int[15];

System.arraycopy(arr,0,copied,1,10);
System.out.println(Arrays.toString(copied)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0]

 

List

  - java.util.ArrayList;

  - java.util.List;

0. 선언

List<Object> list = new ArrayList< Object >;
ArrayList<Object> list = new ArrayList< Object >;

 

 

1. 메소드

add(value) ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add(1,"129");
pitches.add("142");   //[138,129,142]
get(index) piches.get(1)   // 129
size() piches.size()   // 3
contains(value) piches.contains("142")   // true
remove(value)
remove(index)
piches.remove("1122")
// false / 결과를 bool 로 리턴 
piches.remove(4)
// 에러 / 결과를 해당항목을 리턴 / 존재하지 않는 인덱스는 에러 

 

 

댓글